# Overview

Audience: Developer

System Architecture

## System architecture

Pyck is a modular microservices platform with a clear separation of concerns, built in Go, that provides a logistics solution for warehousing operations.

### Framework building blocks

The Pyck framework consists of three main components: the **Core** (backend services), the **Web App**, and the **Mobile App**.

**Core:** Backend services consisting of a **GraphQL API** (with Federation), **event streaming** (NATS.io), and **workflow orchestration** (Temporal.io).

**Web App:** Browser-based interface for managing warehouse operations, configuration, and monitoring.

**Mobile App:** Native mobile application for on-the-floor warehouse tasks such as picking, receiving, and inventory management.

### Core components

1. **Gateway Service**
   - Aggregates GraphQL schemas from all services
   - Provides a unified API endpoint
   - Handles authentication and request routing

2. **Domain Services**
   - **Main Data Service**: Core data operations and primary data entities
   - **Inventory Service**: Stock levels, item movements, and inventory management
   - **Management Service**: System configurations and company-related information
   - **Picking Service**: Order picking workflow and processing
   - **Receiving Service**: Inbound shipment processing
   - **File Service**: File storage and document management
   - **Workflow Service**: Background task execution and process automation

### Technical infrastructure

Pyck uses these technologies:

- **GraphQL**: Main API interface with federation across services
- **PostgreSQL**: Primary data storage
- **NATS.io**: Event streaming and service messaging; tenant clients use a separate account, see [NATS configuration requirements](https://docs.pyck.cloud/dev/operations/configuration.md#nats-configuration-requirements)
- **Temporal.io**: Workflow orchestration and reliable task execution
- **Docker**: Containerization for consistent deployment
- **Zitadel**: Authentication and authorization (OIDC/OAuth2)
- **MinIO/S3**: Object storage for files and attachments
- **Kubernetes**: Orchestration

The data model is described in [Concepts](https://docs.pyck.cloud/dev/concepts/building-blocks.md).

### Data storage

Pyck uses a **multi-tenant architecture**. Tenants share one database, and every row carries a `tenant_id`. The services add a tenant filter to every query and check the tenant on every mutation, so a request only sees and changes the data of the tenants it is authorized for. This isolation is enforced in the application, not by PostgreSQL row-level security. Within a tenant, multiple root level repositories (warehouses) can exist.

The movement-based data model also enables **time-travel queries**, allowing you to query inventory state at any historical point in time.

Pyck is designed to handle concurrent API requests without conflicts. Database transactions and stock validations ensure operational consistency, even under concurrent load.

### Service communication

Services communicate through:

1. **GraphQL Federation**: For data queries and mutations
2. **Event Streaming**: Using NATS for asynchronous events
3. **Workflow Orchestration**: Temporal for complex process flows

### Development approach

The codebase follows these principles:

- **Go Backend**: All backend services are written in Go
- **Infrastructure as Code**: Docker Compose and Taskfile for automated setup
- **API-First Design**: GraphQL schema definitions drive implementation
- **Code Generation**: Models and GraphQL adapters are generated using entgo
- **CRUD+ System**: Backend provides common basic functions for all warehouses
- **Process Workflows**: Complex business logic implemented via temporal processes

### Deployment model

Pyck can be deployed as:

- **Local Development Environment**: Using Docker Compose
- **Kubernetes Cluster**: Using Helm charts for production deployment

#### Required environment variables

All Pyck services require `PYCK_ENV`, see [Required environment variables](https://docs.pyck.cloud/dev/operations/configuration.md#required-environment-variables).

### Tenant worker architecture

Pyck implements a per-tenant worker deployment model for Temporal workflows:

- **Automatic Provisioning**: During tenant registration, the system automatically deploys a dedicated Temporal worker for each tenant
- **Kubernetes Integration**: Workers are deployed as Kubernetes custom resources using the temporal-worker-controller
- **Isolation**: Each tenant gets its own worker deployment, ensuring workload isolation and independent scaling
- **Resource Management**: Worker deployments are created in a shared workers namespace with configurable resource limits (CPU: 100m-500m, Memory: 256Mi-512Mi)

#### Worker deployment components

When a new tenant is registered, the following Kubernetes resources are created:

1. **Workers Namespace**: A shared namespace for all tenant workers (e.g., `{environment}-workers`)
2. **TemporalConnection CRD**: Defines the connection to the Temporal service (shared per environment)
3. **TemporalWorkerDeployment CRD**: Creates a dedicated worker deployment for the tenant

#### Worker deployment configuration

Worker deployments can be configured via environment variables:

- **`PYCK_FLAVOUR_GO_WORKER_REPLICAS`**: Number of worker pod replicas per tenant (default: `2`)
  - Controls horizontal scaling of tenant worker deployments
  - Higher values provide better availability and throughput
  - Should be tuned based on expected workflow load per tenant

#### Worker health monitoring

Each Temporal worker automatically exposes a `/health` HTTP endpoint (default port 8080) that verifies the worker is actively polling Temporal. The health check:

- Queries Temporal to confirm this worker's identity appears in the task queue poller list
- Returns **200 OK** when the worker is healthy and polling
- Returns **503 Service Unavailable** when the worker has stopped polling or cannot reach Temporal

The optional settings are listed in [Optional health check configuration](https://docs.pyck.cloud/dev/operations/configuration.md#optional-health-check-configuration).

This health endpoint integrates with Kubernetes liveness probes and fly.io health checks to automatically restart workers that have silently stopped processing workflows.

### Tenant NATS clients

Tenant clients connect to NATS in the tenant account (named by `PYCK_NATS_TENANT_ACCOUNT_NAME`, default `pyck-tenants`, see [NATS configuration requirements](https://docs.pyck.cloud/dev/operations/configuration.md#nats-configuration-requirements)) and read their events through **pull consumers** on their own tenant stream. They can create, inspect and delete consumers through the usual JetStream API (`$JS.API.CONSUMER.CREATE.>` and so on), using one of the tenant's consumer names (`<tenantID>--one` to `<tenantID>--ten`).

**Push consumers are not allowed.** A consumer create request whose config has a `deliver_subject` is refused, whatever the spelling of the key. The client gets a JetStream error answer instead of a consumer:

```json
{
  "type": "io.nats.jetstream.api.v1.consumer_create_response",
  "error": {
    "code": 400,
    "description": "push consumers are not allowed for tenant clients"
  }
}
```

Other answers from the same check:

| Code | Description | Cause |
|------|-------------|-------|
| `400` | `invalid consumer create request` | The request body is not one valid JSON object |
| `503` | `JetStream did not answer` | The create was forwarded but JetStream did not answer within 5 seconds |

Use a pull consumer (for example `jetstream.Stream.CreateOrUpdateConsumer` with nats.go, then `Fetch`, `Consume` or `Messages`) instead of a push subscription.

#### What a consumer can rely on

Delivery is at least once, so plan for duplicates.

- **An event exists once the mutation commits.** A mutation that rolls back leaves no event. The events of a mutation that commits are published after the commit, not at it.
- **Order holds inside one transaction only.** The events of one transaction are published in the order they were written, and when one fails to publish, the rest of its transaction waits for the retry. Between transactions no order is guaranteed.
- **Deduplicate by `event_id`.** The payload of every mutation event and every custom event carries `event_id`, the ID of the outbox entry. It is fixed when the event is written, so it is the same on every publish retry and on every copy of the message. Do not use `id` for this: it is the ID of the entity, which two updates of one entity share. The same ID is the `eventID` of the matching entry in `transactionRouting`, see [What a mutation starts](https://docs.pyck.cloud/dev/developers/mutation-results.md).

#### How consumer creates are handled

The management service creates the consumers of tenant clients. It serves the subject `$PYCK.TENANT.CONSUMER.CREATE.>` in the `pyck` account, and the tenant account imports that subject as `$JS.API.CONSUMER.CREATE.>`. Management refuses a create with a deliver subject and forwards any other create, body only, to JetStream. Without this check a push consumer could deliver a tenant's events into another tenant's stream or the system stream, because NATS permissions do not check a deliver subject.

Operators: see [NATS configuration requirements](https://docs.pyck.cloud/dev/operations/configuration.md#nats-configuration-requirements).
