> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hoox.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# deploy-workers

# 🚀 Deploying to Production

Deploying your algorithmic trading ecosystem to Cloudflare's production edge requires careful orchestration. Because workers communicate internally using fast-path **Service Bindings**, they have strict compile-time and deploy-time dependencies.

This guide outlines our automated deployment sequence, Next.js OpenNext compilation steps, post-deployment URL bindings, and troubleshooting runbooks.

***

## ⛓️ The Strict Deployment Dependency Chain

When you deploy, workers must be uploaded in a specific sequence. If you attempt to deploy the public gateway (`hoox`) before the database or execution engines are live, the deployment will fail because the gateway's compile-time service bindings cannot resolve their targets.

The Hoox CLI automates this dependency hierarchy:

```text theme={null}
[1. D1 Database Schema] ──► [2. d1-worker (SQL Hub)] ──► [3. trade-worker (Execution Engine)]
                                                                    │
    ┌───────────────────────────────────────────────────────────────┘
    ▼
[4. hoox Gateway (Public Router)] ──► [5. agent-worker & telegram-worker]
                                                    │
                                                    ▼
                                            [6. Next.js Dashboard (OpenNext)]
```

### Deployment Order Explained

| Step | Worker                         | Why First?                                                  |
| :--: | ------------------------------ | ----------------------------------------------------------- |
|   1  | D1 Schema                      | Database tables must exist before workers try to read/write |
|   2  | d1-worker                      | SQL hub must be available for other workers' DB operations  |
|   3  | trade-worker                   | Core execution engine — other workers depend on it          |
|   4  | hoox Gateway                   | Public-facing router — needs all internal workers live      |
|   5  | agent-worker + telegram-worker | Background services — can deploy independently              |
|   6  | Dashboard (OpenNext)           | Frontend — depends on gateway and all APIs                  |

***

## ⚡ Deployment CLI Commands

To execute a complete production rollout:

```bash theme={null}
hoox deploy all --auto

# 2. Deploy a single specific worker (e.g. after a custom logic update)
hoox deploy worker trade-worker

# 3. Redeploy only the dashboard
hoox deploy dashboard
```

### Deploy All Flags

| Flag             | Description                               | Example                                 |
| ---------------- | ----------------------------------------- | --------------------------------------- |
| `--auto`         | Automatically resolves dependency order   | `hoox deploy all --auto`                |
| `--skip-tests`   | Skip pre-deploy test suite                | `hoox deploy all --auto --skip-tests`   |
| `--dry-run`      | Preview deployment plan without uploading | `hoox deploy all --auto --dry-run`      |
| `--workers-only` | Skip dashboard deployment                 | `hoox deploy all --auto --workers-only` |

***

## 🔧 Critical Post-Deployment Steps

Once `hoox deploy all` finishes uploading the workers, you must run three final scripts to link webhooks and sync environment databases:

```bash theme={null}
# A. Register your private Telegram Bot webhook with Cloudflare
hoox deploy telegram-webhook

# B. Auto-update and bind internal Service URLs across all workers
hoox deploy update-internal-urls

# C. Sync and apply the default CONFIG_KV manifest variables
hoox deploy kv-config
```

### Why These Steps Are Required

<ol>
  <li>
    <strong>Telegram Webhook Registration</strong> — Tells Telegram's Bot API
    where to send user messages. Without this, your bot will be unreachable.
  </li>

  <li>
    <strong>Internal URL Binding</strong> — After deployment, each worker gets a
    new URL. This command updates all Service Binding references so workers can
    find each other.
  </li>

  <li>
    <strong>KV Manifest Sync</strong> — Ensures your runtime configuration (kill
    switch, rate limits, routing rules) matches the freshly deployed workers.
  </li>
</ol>

***

## 🖥️ Next.js Dashboard Deployment (OpenNext)

The Hoox Command Center is a modern Next.js 16 web application that runs directly on Cloudflare Workers using the **OpenNext adapter**.

When you run `hoox deploy dashboard`:

<ol>
  <li>
    The CLI compiles the Next.js app using the <strong>Turbopack</strong> build
    engine.
  </li>

  <li>
    The <strong>OpenNext</strong> compiler bundles the application logic into a
    single Edge-compliant V8 worker file: <code>.open-next/worker.js</code>.
  </li>

  <li>
    All static files (images, JS chunks, CSS) are isolated under{" "}
    <code>.open-next/assets/</code>.
  </li>

  <li>
    The CLI uses <code>wrangler</code> to deploy the worker and binds the static
    assets to Cloudflare's <strong>ASSETS binding</strong>, serving pages at
    sub-millisecond speeds.
  </li>
</ol>

```bash theme={null}
# Build and deploy the Next.js Dashboard to Cloudflare Workers
hoox deploy dashboard

# Rebuild dashboard only (after UI changes)
hoox deploy dashboard --force-rebuild
```

### Dashboard Features

Once deployed, the Command Center provides:

* Real-time portfolio value and P\&L tracking
* Win rate statistics and trade history charts
* Live position monitoring with one-click close
* Risk settings adjustment (no redeploy needed)
* AI-powered trade analysis chat

***

## 🔄 Routine Update & Upgrade Workflow

To pull the latest platform releases, run local tests, and update your active production edge:

```bash theme={null}
# 1. Fetch latest changes and update git submodules recursively
git pull --recurse-submodules

# 2. Install updated dependencies
bun install

# 3. Execute the full local CI verification pipeline
hoox test

# 4. Run pre-deploy health check
hoox repair check

# 5. Roll out updates globally to the Cloudflare Edge
hoox deploy all --auto
```

### Rollback Procedure

If the new deployment causes issues:

```bash theme={null}
# 1. Revert git to previous release
git checkout v2.0.0  # or your previous tag

# 2. Redeploy the stable version
hoox deploy all --auto
```

***

## 🛠️ Post-Deployment Troubleshooting Matrix

| Error Code / Symptom          | Primary Root Cause                                | Guided Resolution                                                                                                                 |
| :---------------------------- | :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------- |
| **`502 Bad Gateway`**         | Service binding target is missing or has crashed. | Ensure the dependency worker (e.g., `trade-worker`) has been deployed successfully. Run `hoox deploy all` to rebuild all bonds.   |
| **`503 Service Unavailable`** | The Global Kill Switch is active in KV.           | Verify switch state: `hoox monitor kill-switch show`. If safe, restore trading: `hoox monitor kill-switch off`.                   |
| **`401 Unauthorized`**        | Webhook request failed passkey check.             | Audit KV authorization key: `hoox config kv get webhooks:api_key`. Verify the payload `apiKey` matches this value.                |
| **`409 Conflict`**            | Durable Object intercepted a duplicate trace ID.  | Verify TV alert settings. Do not configure rapid-fire duplicate alerts within the same minute unless idempotency keys are unique. |
| **Dashboard shows 500**       | Next.js build failed or D1 schema mismatch.       | Re-run `hoox deploy dashboard` and check logs: `hoox logs tail dashboard`.                                                        |
| **Telegram bot unresponsive** | Webhook URL expired or token rotated.             | Re-register: `hoox deploy telegram-webhook` and verify token: `hoox secrets check`.                                               |

***

<Tip>
  By utilizing **Smart Placement** in your production builds, Cloudflare will
  automatically route execution to the edge nodes located geographically closest
  to your exchanges (Frankfurt, Tokyo), ensuring high-speed fills!
</Tip>

### 🔗 Next Steps

* [**Real-Time Observability & Monitoring**](monitor-trading) — Audit live fills, tail console logs, and run health diagnostics.
* [**System Self-Healing & Repair**](repair) — Rebuild broken bindings and recover from deployment anomalies.
* [**Infrastructure Management**](manage-infra) — Provision and inspect KV, Queues, R2, and Vectorize indexes.
