Skip to content
Pyck docs

You are reading the Dev docs (main @ e991a08). They can differ from the released product.Dev docs, not the release

Switch to LatestLatest

Workflows in Pyck

Audience Developer

Pyck combines the Temporal workflow engine with our CRUD+ API to build warehouse software. This document covers the workflow architecture, the integration points and the development patterns.

Logistics processes are defined as Temporal workflows, primarily in Go, as this is the Pyck SDK that is currently available, though Temporal itself supports multiple languages. The Pyck Go SDK is optional and serves as a convenience layer; workflows can also be implemented without it.

For Pyck-specific workflow concepts, see Workflows (Concepts). For details on authoring Temporal workflows, refer to the Temporal Go SDK documentation.

  1. Pyck Core Services: Our CRUD+ microservices providing foundational warehouse functionality
  2. Temporal Service: Durable execution service integrated within our core
  3. Database: Persistent storage for both Pyck services and Temporal
  4. API Layer: GraphQL API from Pyck services and gRPC API from Temporal
  5. External Workflows: Custom workflow implementations that operate outside the core system
  6. Frontend Applications: Mobile and web UIs that interact with the system
┌─────────────────────────────────────────────┐
│ pyck Core │
│ │
│ ┌─────────────┐ ┌─────────────────┐ │
│ │ │ │ │ │
│ │ Database │◄───┤ Core Services │ │
│ │ │ │ │ │
│ └─────────────┘ └────────┬────────┘ │
│ ▲ │
│ │ │
│ ┌─────────────┐ │ │
│ │ │ │ │
│ │ Temporal │────────────┘ │
│ │ │ │
│ └─────────────┘ │
│ │
└─────────────┬──────────────┬────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌────────────────┐
│ │ │ │
│ GraphQL API │ │ gRPC API │
│ │ │ (Temporal) │
└────────┬────────┘ └────────┬───────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ External Systems │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ │ │ │ │
│ │ Workflows │────────────────►│ Frontend Apps │ │
│ │ │ │ │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Workflows never lose state, even when systems fail, and business logic continues despite network failures or API outages. Workflows can run for days, weeks or months. Temporal retries failed tasks automatically, with retry policies you configure for intermittent failures. It also keeps the complete history and the real-time status of every workflow execution.

Pyck automatically provisions dedicated Temporal workers for each tenant during registration:

  • Automatic Setup: When a tenant is registered via the registerTenant mutation, the system automatically creates a Kubernetes-based Temporal worker deployment for that tenant
  • Isolation: Each tenant runs workflows in its own dedicated worker, ensuring workload isolation
  • Kubernetes Native: Workers are deployed using the temporal-worker-controller as TemporalWorkerDeployment custom resources
  • Namespace Mapping: Each tenant’s worker connects to a Temporal namespace matching the tenant ID
  • Configuration: Worker deployments include environment-specific settings for Temporal connection, Pyck gateway URL, and tenant credentials
  1. Project Structure: A typical warehouse workflow project includes directories for workflow definitions, activity implementations, data models, API clients, worker service entry point, and tests.

  2. Dependencies: Workflow projects require dependencies for the Temporal SDK and Pyck client libraries.

A workflow is triggered by subscriptions, also called workflow signals. A worker registers its workflows and their subscriptions with the Pyck GraphQL API (registerWorkflow, which requires a workerID) and keeps them alive:

  1. Temporal Registration: Workflows and activities are registered with the Temporal worker.
  2. Subscription Registration: When the worker starts, it registers its own workflows and their subscriptions with the Pyck API. Each subscription names an event topic, a signal type and an optional filter rule.
  3. Heartbeat: The worker refreshes its subscriptions with a heartbeat (default every 5 minutes, PYCK_WORKER_REGISTRATION_HEARTBEAT_INTERVAL). A subscription expires after PYCK_WORKFLOW_SUBSCRIPTION_TTL (default 1 hour) without a heartbeat, and the workflow service then removes it.
  4. Stop: On a clean stop, the worker calls unregisterWorker, which marks its subscriptions as stopped. Nothing is deleted: a stopped subscription keeps routing until its TTL lapses, unless another worker holds running subscriptions for the same workflow.

The subscriptions map workflows to specific event types in the system. For example, a workflow named “TemporalWorkflowPicking_OrderCreate” would be triggered by the “OrderCreate” event. See Triggering a Workflow for the user-facing view.

Workflow IDs in Pyck are generated deterministically. A workflow tied to a specific data entity can be identified by that entity, and a duplicate workflow for the same entity is prevented:

  • With pyck_data_id: When pyck_data_id is present in the search attributes, it is used as the suffix for the workflow ID (e.g., WorkflowName_<pyck_data_id>)
  • Without pyck_data_id: When no pyck_data_id is provided, a new UUID is generated as the suffix (e.g., WorkflowName_<uuid>)

Pyck uses Temporal search attributes to enable filtering, querying, and grouping of workflow executions. These search attributes are automatically configured when Pyck initializes:

  • pyck_data_id: Links the workflow to a specific data entity (e.g., order ID, shipment ID)
  • pyck_workflow_assignee: The ID of the user assigned to the workflow
  • pyck_workflow_name: The name of the workflow being executed
  • pyck_tenant_id: The tenant context for multi-tenant deployments
  • pyck_data_type: The type of data entity the workflow operates on
  • pyck_service: The Pyck service that owns the workflow
  • pyck_group_by: Custom grouping criteria for categorizing and filtering workflows
  • pyck_title: Human-readable per-workflow display label shown in the UI (set via workflowsdk.SetWorkflowTitle)
  • pyck_group_title: Human-readable label for the workflow group header (set via workflowsdk.SetGroupTitle, pairs with pyck_group_by)
  • pyck_sort_key: Integer value used by the UI to impose a stable display order on workflow executions
  • pyck_transaction_id: The ID of the transaction of the mutation that triggered the workflow (Keyword). The mutation returns it as transactionID, and workflowExecutions(where: {transactionID: ...}) lists the executions it started
  • pyck_workflow_is_assignable: Whether the workflow can be assigned to a user (Boolean). A workflow that never wrote it counts as assignable, so isAssignable: true also matches it. The SDK sets it with workflowsdk.SetWorkflowIsAssignable
  • pyck_workflow_targets: The client surfaces the workflow is meant for (KeywordList of WEB, MOBILE or SETUP). The SDK sets it with workflowsdk.SetWorkflowTargets, and workflowExecutions filters on it with targets and targetsNotIn

Search attributes can be used to query and filter workflows through the Temporal API:

// Example: Find all picking workflows for a specific order
const workflows = await temporal.workflow.list({
query: 'pyck_workflow_name="OrderPicking" AND pyck_data_id="order-123"'
});
// Example: Find all workflows assigned to a user
const userWorkflows = await temporal.workflow.list({
query: 'pyck_workflow_assignee="user-456"'
});
// Example: Group workflows by custom criteria
const groupedWorkflows = await temporal.workflow.list({
query: 'pyck_group_by="priority-high" AND pyck_service="picking"'
});
// Example: Order workflows by sort key
const orderedWorkflows = await temporal.workflow.list({
query: 'pyck_sort_key >= 10 AND pyck_sort_key <= 99'
});

The Pyck SDK exposes helpers to set per-workflow display metadata as Temporal search attributes. The UI uses these labels for workflow lists and group headers, and clients can filter/sort directly on them through the GraphQL workflowExecutions query.

Use workflowsdk.SetWorkflowTitle to write the pyck_title search attribute, which is the per-workflow display label shown in lists and dashboards.

import "github.com/pyck-ai/pyck/backend/workflowsdk"
func MyWorkflow(ctx temporalworkflow.Context, input MyInput) error {
// Set the display label so the UI can show a human-readable title
// and so callers can query workflowExecutions(where: {title: ...}).
if err := workflowsdk.SetWorkflowTitle(ctx, "SKU-123"); err != nil {
return err
}
// ... rest of the workflow
return nil
}
  • Passing an empty string clears the attribute so the frontend falls back to the workflow type name:

    workflowsdk.SetWorkflowTitle(ctx, "") // unset
  • The attribute is a Temporal Keyword type; both equality and prefix/suffix predicates are available via the GraphQL title* filters.

  • workflowsdk.GetWorkflowTitle(ctx) reads the current value.

Use workflowsdk.SetGroupTitle to write the pyck_group_title search attribute, which is the human-readable label for the workflow group header. It pairs with pyck_group_by (the technical join key); set both together so the UI can group workflows under a shared label.

if err := workflowsdk.SetGroupBy(ctx, "order-42"); err != nil {
return err
}
if err := workflowsdk.SetGroupTitle(ctx, "ORDER-42"); err != nil {
return err
}
  • Passing an empty string clears the attribute so the frontend falls back to "No Group".
  • workflowsdk.GetGroupTitle(ctx) reads the current value.

The pyck_sort_key search attribute can be set from within a workflow using the workflowsdk to control the display order of workflow executions in the UI:

import (
"github.com/pyck-ai/pyck/backend/workflowsdk"
)
// Set a sort key to control display order
func MyWorkflow(ctx workflow.Context) error {
sortKey := int64(42)
if err := workflowsdk.SetSortKey(ctx, &sortKey); err != nil {
return err
}
// ... rest of workflow logic
// Clear the sort key (falls back to default start-time ordering)
if err := workflowsdk.SetSortKey(ctx, nil); err != nil {
return err
}
return nil
}
// Read the current sort key
func CheckSortKey(ctx workflow.Context) {
sortKey := workflowsdk.GetSortKey(ctx)
if sortKey != nil {
// Sort key is set to *sortKey
} else {
// Sort key is not set, will use default ordering
}
}

The sort key is particularly useful when you need workflows to appear in a specific order in the UI, rather than relying solely on start time. Pass nil to SetSortKey to unset the attribute and fall back to default start-time ordering.

workflowsdk.SetWorkflowMemo and the associated WorkflowMemo struct (with Title, Subtitle, and Data fields) have been removed. Memo fields are opaque to Temporal Visibility and cannot be indexed; search attributes are fully queryable.

Before:

workflowsdk.SetWorkflowMemo(ctx, workflowsdk.WorkflowMemo{
Title: "SKU-123",
Subtitle: "order-uuid",
Data: map[string]any{"priority": "high"},
})

After:

// The per-workflow title and the group label are now first-class search
// attributes. Custom auxiliary data should move into the workflow input,
// the workflow state, or pyck_group_by depending on its purpose.
workflowsdk.SetWorkflowTitle(ctx, "SKU-123")
workflowsdk.SetGroupBy(ctx, "order-uuid")
workflowsdk.SetGroupTitle(ctx, "ORDER UUID")

The signal router also accepts pyck_title and pyck_group_title keys when propagating attributes from incoming signal payloads, alongside the existing pyck_workflow_assignee and pyck_group_by keys.

Workflows in Temporal are defined as functions that orchestrate a series of activities. A typical picking workflow would include steps like:

  • Fetching order details
  • Allocating inventory
  • Generating picking tasks
  • Updating mobile app UI for picker
  • Waiting for picking completion
  • Processing results and updating inventory

Workflows control frontend behavior through a combination of:

  1. Activity Properties: Each workflow activity can define UI properties that should be displayed
  2. Update Handlers: Workflows wait for user input through Temporal update handlers
  3. NextActivityName: Defining the next activity tells the frontend what screen to show

Workflows are triggered by events from the system through an advanced signal routing mechanism that differentiates between START and INTERMEDIATE signals:

  1. START Signals: Create new workflow instances when triggered
  2. INTERMEDIATE Signals: Forward signals to already running workflow instances

When an event occurs in the Pyck system:

  • The system uses JetStream-based routing to determine which workflows should be triggered
  • START signals will create new workflow instances. A start whose workflow ID is already running counts as a success and is recorded as already_running
  • INTERMEDIATE signals will be forwarded to matching running workflows

For example, when an order is created in the system, the “OrderCreate” event is fired, which then triggers the “TemporalWorkflowPicking_OrderCreate” workflow.

Important Breaking Change: As of the latest version, running workflows cannot be reassigned on re-trigger. Attempting to start a workflow that is already running is recorded as already_running and the running execution does not see the event, so a re-trigger cannot start a duplicate execution. Workflows that need every update use Signal-With-Start.

Custom events allow workflows to be triggered by application-specific events sent via the sendCustomEvent GraphQL mutation. Since v0.26.0, custom events have their own dedicated namespace separate from CRUD events.

Pyck publishes events on different NATS subjects based on their type:

  • CRUD Events: pyck.<tenant>.crud.<service>.<schema>.<entity>.<operation>

    • The first segment is the NATS stream name (PYCK_NATS_STREAM_NAME, pyck in the examples) and <entity> is the ID of the entity. Triggering a Workflow shows this subject for a created inventory item
    • Published automatically when entities are created, updated, or deleted
    • Examples: create, update, delete operations
  • Custom Events: pyck.<tenant>.custom.<type>.<entity>.<operation>

    • Published via the sendCustomEvent mutation
    • Custom operation names supported (not limited to create/update/delete)
    • Examples: approve, reject, low_stock_alert, milestone_reached

The two event types use different subjects (crud and custom), so custom events cannot collide with entity CRUD events.

To register a workflow that triggers on custom events, use CustomSignalTopic from the workflowsdk:

import (
"github.com/pyck-ai/pyck/backend/workflowsdk"
)
// Subscribe to a specific custom event type and operation
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
EventType: "tour-creation",
OperationName: "create",
})
// Subscribe to all operations for a custom event type
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
EventType: "inventory-alert",
// OperationName omitted = wildcard
})
// Subscribe with entity ID filtering
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
EventType: "order-approval",
EntityID: orderID,
OperationName: "approve",
})

Unlike CRUD events which only support create, update, and delete operations, custom events support any operation name chosen by the caller:

  • Standard Operations: create, update, delete use their respective start policies
  • Custom Operations: Any other operation (e.g., approve, ping, alert) uses the update policy
    • Allows one run per entity once the previous run has closed
    • Events arriving while a workflow runs are recorded as already_running

Custom events are tenant-scoped and workflows can only subscribe to their own tenant’s events:

  • Each tenant’s custom events are published on subjects containing that tenant’s ID
  • Workflows attempting to subscribe to another tenant’s custom events will be rejected
  • An unset TenantID subscribes to every tenant the registering user can read; a TenantID of a tenant the user cannot read is rejected.

Migration Required:

Before:

// This no longer receives custom events
signal.NewStartSignal(workflowsdk.SignalTopic{
ServiceName: "management",
SchemaName: "tour-creation",
OperationName: "create",
})

After:

// Use CustomSignalTopic for custom events
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
EventType: "tour-creation",
OperationName: "create",
})

Important: Deploy the migrated workflows together with the Pyck platform update. Deployed earlier, they fail to register; deployed later, they miss events.

The communication between Temporal workflows and the frontend when waiting for user input follows a specific stateful pattern:

Workflows maintain their state through a query mechanism that allows external systems to inspect their current state without affecting execution:

  1. Query Handler: Each workflow exposes its current UI state through a query handler for “nextActivityProperties”
  2. Activity Definition: The workflow defines what activity the user should perform next
  3. Update Handlers: The workflow registers update handlers to receive the user input from the frontend
  4. Waiting for Input: The workflow pauses execution while waiting for user input

The frontend interacts with workflows through a well-defined cycle:

  1. Discover Workflows: Frontend finds workflows assigned to the current user via the workflowExecutions GraphQL query, filtered by assignee
  2. Get Current Activity: The system retrieves the current activity information from the workflow
  3. Render UI Components: Frontend displays the appropriate UI based on the activity properties
  4. Collect User Input: User interacts with the UI and provides the requested information
  5. Submit Input and Get Next Step: When the user submits input, the frontend calls a single GraphQL mutation (submitUserDataInput) that:
    • Sends the user input to the workflow
    • Waits for the workflow to process the input
    • Returns the next activity in the same response

The frontend does not need to poll for the next activity after submitting user input. The single GraphQL mutation returns both the acknowledgment of the submitted data and the instructions for the next step.

When the submitUserDataInput GraphQL mutation is called:

  1. Update Sending: The GraphQL resolver sends the user input to the workflow as a Temporal update
  2. Synchronous Waiting: The resolver waits until the update has completed and uses its result
  3. Response with Next Step: The resolver does not poll the workflow state. Once the update has completed, the mutation returns the update’s result (result) together with the workflow type, ID and run ID

Inside the workflow, when it receives user input:

  1. Update Reception: The workflow’s update handler receives the user input
  2. State Update: The workflow updates its activity state to indicate the current activity is passed
  3. Input Processing: The workflow processes the input, often calling an activity
  4. Next Activity Definition: The workflow defines the next activity for the user
  5. State Exposure: The updated state becomes available to the GraphQL resolver

We use BPMN for visual workflow design and translate it to Temporal code:

  1. BPMN Process: Designed with logistics team for business requirements
  2. Activities: BPMN tasks become Temporal activities
  3. Gateways: BPMN gateways become workflow conditions
  4. Events: BPMN events map to Temporal signals/triggers

The workflow directory structure typically follows this pattern:

processes/
{priority}_{domain}/
{id}_{event}/
activities/ # Activity implementation
domain/ # Data models
workflows/ # Workflow definition
{event}.bpmn # Visual workflow design

For a practical example, see our reference implementation: https://github.com/pyck-ai/pyck-customer-template

Topic Practice
Idempotency Make all activities idempotent so retries are reliable.
Deterministic workflows Keep workflows deterministic by moving non-deterministic code to activities.
Error handling Use retry policies that fit each failure type.
Testing Write tests for workflows and activities.
Monitoring Set up monitoring and alerting using Temporal metrics.
Versioning Use versioning for workflow changes, so in-flight workflows keep working.