Skip to content

Latest commit

 

History

History
262 lines (230 loc) · 17.4 KB

production-eks.md

File metadata and controls

262 lines (230 loc) · 17.4 KB

Production deployment on EKS

The API and the web UI run as one pod (two containers), and any number of those pods may share one Postgres and one Redis: set api.replicas, or enable api.autoscaling and let the HPA own the count. Every pod serves the UI, the REST API and the WebSockets and runs the queue workers. Upgrades use Recreate (migrations run at boot, so no old pod serves against a newer schema): each deploy is a control-plane gap of seconds, after which browsers, apps and Local daemons reconnect. Agent pods scale independently within each workspace, owner and access profile.

What the pods share lives in the database and Redis (docs/plans/scale-out.md): a run's concurrency claim is a Postgres advisory lock, every periodic sweep runs under a lease in leases and is safe to overlap anyway (ticket claims, a compare-and-swap on a schedule's next tick, one active review per PR), inbound webhook deliveries and WebSocket upgrade tokens are rows, and repeat jobs are BullMQ job schedulers with stable ids, so pods booting in any order leave one schedule per tick. An agent run is attached to one pod at a time and outlives it: when that pod goes away another one re-attaches from the run's consumed offset (docs/reconciliation.md). Session chat reaches viewers on every pod over the session bus. An Optio Local daemon is one WebSocket on one pod, which holds the host's lease (local-host:<id>); viewers, REST calls and workers on the other pods reach it over Redis pub/sub, and when that pod goes away the daemon reconnects to another and its viewers follow (docs/optio-local.md).

What stays per pod: the WebSocket connection cap (50 sockets per client address, counted by the pod that holds them, so with N pods an address may hold up to N times that), and caches each pod rebuilds on its own: the GitHub App installation token (each pod mints its own hour-long token), the health, version and setup checks, and the metrics gauges. None of them is correctness state.

Managed services and existing Secrets

Start with helm/optio/values.production.yaml. Set your public hostname, ingress controller and TLS certificate. Use managed PostgreSQL and Redis, with encryption, backups and credentials appropriate to your deployment. Redis must retain queue state and must not evict queue keys. Enable TLS in the connection URLs according to your managed service's requirements (rediss:// for Redis).

The ingress sends /api straight to the API, so set rateLimit.trustProxy (OPTIO_TRUST_PROXY) to the addresses the ingress controller or load balancer connects from (for example the pod or VPC CIDR). Without it every client shares the ingress's address for the per-client rate limits (the auth routes' 10 a minute among them). List only proxies: an address a client can reach the API from directly could then choose its own X-Forwarded-For.

Redis can be a single server (externalRedis.mode: standalone, the default) or a Redis Cluster (externalRedis.mode: cluster). ElastiCache Serverless always runs in cluster mode: set mode: cluster, use its TLS endpoint (rediss://) with an RBAC user, and keep the hash-tagged BullMQ prefix (externalRedis.queuePrefix, default {optio}). Serverless evicts only keys with a TTL, so queue state is never dropped silently, but a cache at its storage limit rejects writes: set its maximum data storage and alarm on BytesUsedForCache and Evictions. Before switching, run pnpm --filter @optio/api redis:smoke against the cache. See docs/redis.md.

Provision Kubernetes Secrets in the Optio namespace using your secret manager (for example External Secrets Operator), then reference individual keys:

postgresql:
  enabled: false
redis:
  enabled: false
existingSecrets:
  DATABASE_URL: { name: optio-runtime, key: database-url }
  REDIS_URL: { name: optio-runtime, key: redis-url }
  OPTIO_ENCRYPTION_KEY: { name: optio-runtime, key: encryption-key }
  GOOGLE_OAUTH_CLIENT_ID: { name: optio-sign-in, key: client-id }
  GOOGLE_OAUTH_CLIENT_SECRET: { name: optio-sign-in, key: client-secret }
  # Generic OIDC instead:
  # OIDC_ISSUER_URL: { name: optio-sign-in, key: issuer }
  # OIDC_CLIENT_ID: { name: optio-sign-in, key: client-id }
  # OIDC_CLIENT_SECRET: { name: optio-sign-in, key: client-secret }

existingSecrets maps environment variable names to {name, key} references on the API container. It also supports GitHub/GitLab OAuth and other API settings. Explicit Secret references override the chart's envFrom defaults. For database, Redis, encryption and OAuth keys, their inline values are omitted from the chart-generated Secret when a reference exists. Missing Secrets/keys prevent pod startup. Secret values are never looked up by Helm or stored in Helm values. Existing provider-specific github.app.existingSecret, APNs and FCM settings continue to work. Restart the deployment after rotating an external Secret: Kubernetes does not refresh existing environment variables in running containers.

Generate the encryption key once (openssl rand -hex 32) and back it up separately from the database. Keep the same key across upgrades and restores: replacing it makes saved credentials unreadable and invalidates pod credential-helper keys. Changing a value in the secret manager is not an encryption-key migration.

Storage, identity and network

Install/configure the EBS CSI driver and choose a StorageClass available in your cluster; gp3 below is an example, not a class the chart installs:

agent:
  pvc:
    storageClass: gp3
    size: 10Gi
  cache:
    storageClass: gp3
  serviceAccount:
    create: true
    # name defaults to <release>-agent
    annotations: {}

StatefulSet repo pods have separate persistent claims for /home/agent and /workspace, plus optional caches. Claims and pod names are partitioned by workspace, owner, purpose and explicit work access settings. A sharable interactive session gets its own pod. Budget storage/claim quotas for this increased isolation; the production example quota is a starting point, not a capacity recommendation. Retained claims are not automatically deleted on idle scale-down or recovery. Back them up if unpushed work matters. Inventory and remove retained claims only after confirming their work is no longer needed. Bare pods/pooled Jobs do not provide the same workspace persistence as repo StatefulSets.

With resourceQuota.enabled, Kubernetes rejects any container that has no cpu/memory requests and limits. Most containers Optio creates set none unless the repo or Job configures them (repo, Job, agent and session pods, and the chart's own Postgres init and helm test pods), so the chart also renders a LimitRange (resourceQuota.limitRange, on by default) whose defaultRequest and default fill in the missing values. A few things to size for:

  • default is a hard cap per container, and a repo pod's one main container hosts maxAgentsPerPod agents and their builds. The 2 CPU / 4Gi defaults are a floor for small agents; raise them for heavier work.
  • Every defaulted agent pod counts default against limits.cpu / limits.memory in resourceQuota.hard. With the production example (40 CPU / 80Gi of limits, minus the chart's own pods), that is roughly 18 agent pods, well short of pods: "50"; raise the limits or lower default to match.
  • A repo or Job that sets a request above default must also set its own limit: the LimitRange fills default in as the limit, and Kubernetes rejects a container whose request exceeds its limit.
  • The defaults apply at admission, so pods already running keep their old (unlimited) resources until Optio recreates them.

The API itself needs no volume. Marketplace skills are synced into PostgreSQL (installed_skill_files) and runs read them from there, so the chart no longer has the former installedSkillsCache ReadWriteOnce PVC (a value left in an override file is ignored). helm upgrade deletes the <release>-installed-skills-cache claim if it was enabled; nothing in it needs a backup, because the first sync after the upgrade re-clones each skill from its source and writes its files to the database.

Agents use a separate service account, with no API-server RBAC and no automounted Kubernetes token. Configure agent.serviceAccount.annotations for an intentionally shared agent IAM role if required. Do not give it the API's permissions. An agent IAM role is shared by agents using that account; per-owner cloud permissions should use scoped Connections or a separately isolated deployment. Restrict node instance metadata access and node roles accordingly.

Use a CNI that enforces NetworkPolicy; simply installing YAML does not enforce network isolation. The chart's optional policy selects every Optio-created agent pod. It allows CoreDNS in kube-system, the Optio API port, and public HTTP(S), excluding private, loopback, link-local/metadata and multicast ranges. Setting networkPolicy.deniedEgressCidrs adds exclusions for deployment-specific ranges; an empty list does not remove the built-in restrictions. Repo-level restricted policies allow public HTTPS, CoreDNS and the API port and must be installed before the pod starts; a policy-creation error fails provisioning. The chart's networkPolicy.enabled=false local default does not disable an explicitly restricted repo's policy requirement. Docker Desktop does not enforce these rules.

Review egress requirements for git providers, model APIs, Connections, DNS and the internal credential endpoint. Private services can be listed by address or namespace in networkPolicy.internalEgress (see Agent network policy; host names, ranges wider than /8, loopback, link-local/metadata ranges and Optio's own namespace are refused at render time); other private destinations or nonstandard DNS require explicit destination/port rules under networkPolicy.extraEgress; those grants apply to every agent pod. Do not grant PostgreSQL, Redis or instance metadata. Review custom pod/service CIDRs and CNI behavior before production traffic. Standard NetworkPolicy is IP/port based and does not enforce a provider-domain allowlist. Apply least-privilege network and IAM policies for your environment. Containers share a kernel: pods are useful process/filesystem boundaries, not a VM boundary against hostile tenants. For mutually untrusted tenants, use separate clusters/accounts or an independently validated sandbox runtime. See Kubernetes multi-tenancy and AWS tenant isolation guidance.

Upgrade and recovery behavior

Pin matching API, web and agent image versions. Back up PostgreSQL, encryption keys and needed PVC data before the upgrade. Deploy the new agent images too: recoverable pod terminals require tmux.

The agent images pin Claude Code 2.1.310 to include the worktree, plugin revision and edit/write race security fixes. After building an agent image, run node scripts/smoke-claude-exec.mjs <image> on each deployment CPU architecture and kernel family. This network-disabled test exercises docker exec, a native Bash tool and streamed completion against a local fake provider. claude --version alone does not exercise the Bun exec/GC crash that prompted the old vulnerable 2.1.112 pin. Updating an image tag does not replace existing agent pods; drain or recreate those pods after preserving active work.

The base image also pins npm and Copilot to audited releases. Experimental OpenClaw remains on its Node 22 compatible release; images/openclaw/package.json and its lockfile override its MCP SDK, Undici and Zod dependencies to fixed versions. Audit that separate dependency tree with npm audit --prefix images/openclaw --omit=dev when updating the agent image. Pi also has a separate lockfile at images/pi, with its Undici dependency fixed; npm audit --prefix images/pi --omit=dev checks that tree. The PI_VERSION build argument still permits explicit overrides, which need their own validation. The image uses npm 12, which blocks unapproved dependency install hooks. Repos whose setup needs native-module or other install hooks must declare their reviewed allowScripts policy; the image explicitly approves only the harness packages needed during its own build.

Old pods are deliberately not relabeled as isolated: their files may contain credentials from several owners. New work uses new isolated pools. Existing sessions retain their history and expose a legacy-pod recovery notice; a new isolated session is required to create a collaboration link. Preserve/commit any uncommitted work before ending old sessions. The old deployment-wide Git helper key is rejected by default. OPTIO_ALLOW_LEGACY_GIT_CREDENTIALS=1 re-enables the old cross-owner credential capability and should not be used in a secure deployment. A pod's helper key is also bound to its one repo: with a GitHub App, the installation token it gets is limited to that repository (repositories: [name]), never the whole installation, and a pod on a non-GitHub repo gets none. Helper keys minted before that binding (no repo in the scope) are refused by the same default; new runs in an existing repo pod sign in with a fresh key, but a pod's own clone credential and older interactive sessions need the pod recreated. Pods with no repo keep an installation-wide token. Rotate credentials that may already have been exposed; isolation cannot retract secrets previously read by a co-resident process.

The session recovery endpoint (GET /api/session-recovery/{pod|local}/{id}) and web session banner distinguish live, reconnecting, resumable, lost and ended sessions:

Interruption Behavior
Browser/network disconnect Reattach to the existing tmux shell or Local PTY; chat continues saving output. No input is automatically resent.
API restart/upgrade Local daemons reconnect with their existing PTYs. Chat receipts become interrupted. Pod Jobs and agents with uncertain execution stop for inspection; Repo Tasks preserve worktrees and become needs-attention/failed, or retain an already-created PR.
Worker/exec stream lost A missing process-exit receipt is an uncertain outcome, not successful completion. Uncertain Jobs do not auto-retry; persistent agents require explicit resume.
Repo StatefulSet pod loss Kubernetes can recreate the pod with retained home/workspace claims. Processes are lost; files survive if the volume survives. Review saved output before continuing.
Bare pod or machine process loss Recorded output remains. Resume an agent conversation only when its files still exist; otherwise start fresh deliberately.
Kubernetes API temporarily unavailable Retain work and report reconnecting; a failed status request is not evidence the pod is gone.

Chat requests carry durable UUID receipts: repeating an accepted request ID cannot run the prompt again, even after API restart. Database claims and in-pod locks prevent overlapping attempts. Incomplete repository setup is preserved for manual inspection rather than silently repeated. This does not guarantee exactly-once side effects in external systems. Explicit retries, external callbacks, agent behavior and a failure between an external write and its acknowledgement still require application-level idempotency or human inspection.

Collaboration links

An owner can create a 24-hour collaboration link from a pod or Local session (API expiry supports 1–168 hours). Recipients must sign in to the same active workspace as a member/admin; viewers cannot control sessions. Redeeming a link grants access to that session's terminal, chat and recorded output. The owner keeps lifecycle and link-management controls. Tokens are random, stored only as hashes, and travel in the URL fragment so normal HTTP access logs/referrers do not receive them.

Revocation closes current collaborators immediately; membership/expiry is checked before input and periodically while streaming (up to 10 seconds). A collaborator can read session credentials and run commands with the session owner's powers; for Local this includes the machine account's capabilities. Revocation stops future access, but cannot undo commands or erase secrets a collaborator already copied.