From 561d84c529afae179cb5cc604bf2672e62b544ee Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 18 Oct 2026 19:04:36 +0800 Subject: [PATCH] docs(deploy): redesign EKS documentation, rename k8s to eks, and add scalable deployment feature --- CHANGELOG.md | 3 +- README.md | 1 + README_CN.md | 1 + docs/configuration/distributed.mdx | 219 +++-------------------- eks/README.md | 234 +++++++++++++++++++++++++ {k8s => eks}/config.yaml | 0 {k8s => eks}/eks-cluster.yaml | 0 {k8s => eks}/garage.yaml | 0 {k8s => eks}/kustomization.yaml | 0 {k8s => eks}/namespace.yaml | 0 {k8s => eks}/postgres.yaml | 0 {k8s => eks}/shumai-server.yaml | 0 {k8s => eks}/shumai-transcode-hpa.yaml | 0 {k8s => eks}/shumai-transcode.yaml | 0 k8s/README.md | 127 -------------- 15 files changed, 257 insertions(+), 328 deletions(-) create mode 100644 eks/README.md rename {k8s => eks}/config.yaml (100%) rename {k8s => eks}/eks-cluster.yaml (100%) rename {k8s => eks}/garage.yaml (100%) rename {k8s => eks}/kustomization.yaml (100%) rename {k8s => eks}/namespace.yaml (100%) rename {k8s => eks}/postgres.yaml (100%) rename {k8s => eks}/shumai-server.yaml (100%) rename {k8s => eks}/shumai-transcode-hpa.yaml (100%) rename {k8s => eks}/shumai-transcode.yaml (100%) delete mode 100644 k8s/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a9be404e..4ba86a25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete Kubernetes example featuring horizontal pod autoscaling (1 to 5 replicas) for media processing with in-cluster Garage S3 storage -* **deploy**: Add AWS EKS cluster deployment configuration and documentation with AWS Graviton3 (`c7g.xlarge`) Spot instances for media transcoding +* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring Graviton3 (`c7g.xlarge`) Spot instances and horizontal autoscaling for media processing * **storage**: Support configuring a separate public endpoint (`AWS_PUBLIC_ENDPOINT_URL_S3`) for browser-facing presigned URLs while preserving internal cluster endpoints for backend workers diff --git a/README.md b/README.md index 9a4fa0d1..e992e51e 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab * **Secure Sharing & Collections**: Create private share links and curated media collections for clients, stakeholders, and collaborators. * **Granular Access Control**: Manage workspace permissions with team-level and project-level role-based access control. * **Distributed Transcoding & Workflows via DBOS**: Offload resource-intensive video transcoding and AI agents to a background worker pool orchestrated durably by DBOS on PostgreSQL. +* **Scalable Deployment on Kubernetes**: Horizontally autoscale video transcoding on multiple instances. See [EKS Deployment Example](eks/README.md). * **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline. * **Share Link Watermarking**: Protect shared media with customizable text and image watermarks, and save watermark as reusable templates. * **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored. diff --git a/README_CN.md b/README_CN.md index 173a8354..afd2ff5f 100644 --- a/README_CN.md +++ b/README_CN.md @@ -30,6 +30,7 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让 * **安全分享和合集管理**:可以生成私密分享链接,也能整理成精选合集,方便给客户、同事和合作方查看。 * **细粒度权限控制**:支持按团队、项目设置角色权限,方便管理不同成员的访问范围。 * **基于 DBOS 的分布式转码与工作流**:把吃资源的视频转码和 AI 任务交给后台 worker 池处理,基于 PostgreSQL 由 DBOS 统一持久化编排与调度。 +* **Kubernetes 弹性扩缩容部署**:支持在多个实例上横向自动扩缩容视频转码工作负载。详见 [EKS 部署示例](eks/README.md)。 * **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。 * **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。 * **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。 diff --git a/docs/configuration/distributed.mdx b/docs/configuration/distributed.mdx index 56ae6aff..229f006b 100644 --- a/docs/configuration/distributed.mdx +++ b/docs/configuration/distributed.mdx @@ -130,219 +130,40 @@ When running multiple replicas of the transcode or agent worker across multiple --- -## Kubernetes Deployment & Autoscaling (HPA) +## Scalable Deployment on Kubernetes & AWS EKS -Shumai provides an out-of-the-box Kubernetes configuration under `k8s/` showcasing horizontal scalability for media processing. Because DBOS manages task queues directly within PostgreSQL, transcode workers are completely stateless and can scale dynamically with workload demand. - -### Architecture +For production cloud deployments requiring high-throughput media processing, Shumai can be deployed on Kubernetes or **AWS Elastic Kubernetes Service (AWS EKS)** with automated horizontal autoscaling. ```mermaid graph TD - User([User / Web Browser]) -->|Port 3000| Server[Pod: shumai-server
SHUMAI_WORKERS=agent] - Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18
Service: shumai-postgres)] - Server -->|Direct Uploads / Stream Proxies| Storage[(Garage S3
Service: garage:3900)] + User([User / Web Browser]) -->|Port 80/3000| Server[Pod: shumai-server
SHUMAI_WORKERS=agent] + Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18)] + Server -->|Direct Uploads / Stream Proxies| Storage[(S3 / Garage Storage)] DB -->|Poll transcode_queue| Worker1[Pod: shumai-transcode-1] - DB -->|Poll transcode_queue| WorkerN[Pod: shumai-transcode-N
Autoscaled Replicas: 1..5] + DB -->|Poll transcode_queue| WorkerN[Pod: shumai-transcode-N
Autoscaled: 1..5 Replicas] Worker1 -->|Fetch Source / Store Proxies| Storage WorkerN -->|Fetch Source / Store Proxies| Storage - HPA[HorizontalPodAutoscaler
Target: 70% CPU
min: 1, max: 5] -.->|Autoscale| WorkerN + HPA[HorizontalPodAutoscaler
Target: 70% CPU
min: 1, max: 5] -.->|Autoscale Pods| WorkerN + CA[Cluster Autoscaler] -.->|Autoscale c7g.xlarge Spot Nodes| WorkerN ``` -### Components +### Key Architectural Highlights -The `k8s/` directory includes a self-contained Kustomize stack: +- **Decoupled Stateless Workers**: The main web and API server runs on lightweight general compute (`SHUMAI_WORKERS=agent`), delegating media transcoding to background workers orchestrated via DBOS task queues in PostgreSQL. +- **Dedicated Graviton3 Spot Compute (`c7g.xlarge`)**: Media encoding runs on 4 vCPU / 8 GiB RAM AWS Graviton3 Spot instances (~$0.06/hr), utilizing ARM64 FP16/SVE vector optimizations to achieve up to 40% better encoding performance at minimal cost. +- **1:1 Pod-to-Node Scaling**: Worker pods request `3000m` CPU, guaranteeing that each active transcoding job gets an entire dedicated 4 vCPU `c7g.xlarge` instance without CPU throttling. +- **End-to-End Autoscaling**: Kubernetes HPA detects encoding load and scales worker pods (1 to 5 replicas), while Kubernetes Cluster Autoscaler provisions and terminates underlying EC2 Spot instances automatically. -1. **`shumai-server`**: Main dashboard and REST API handling web traffic and AI agent tasks (`SHUMAI_WORKERS=agent`). -2. **`shumai-transcode`**: Dedicated transcoding worker pool running `shumaione/shumai-transcode:latest` with `CONCURRENCY_TRANSCODE=1`. Each pod receives its unique identity via the Kubernetes Downward API (`POD_NAME`). -3. **`garage`**: Lightweight in-cluster S3-compatible storage powered by `dxflrs/garage`, automatically initialized with bucket `shumai` and pre-configured credentials. -4. **`shumai-postgres`**: PostgreSQL database with `pgvector:pg18` hosting application data and DBOS workflow queues. -5. **`shumai-transcode-hpa`**: `HorizontalPodAutoscaler` (`autoscaling/v2`) targeting 70% CPU utilization, scaling between **1 and 5 replicas**. +### Complete Deployment Example & Source Code -### Deploying the Stack +For the full, production-ready manifests, declarative `eksctl` cluster configuration, and step-by-step walkthrough, see the **[EKS Deployment Example](https://github.com/shumaiOne/shumai/tree/main/eks)** in the Shumai repository: -Deploy the entire stack with a single command: +👉 **[View the EKS Deployment Guide & Manifests on GitHub](https://github.com/shumaiOne/shumai/tree/main/eks)** -```bash -kubectl apply -k k8s/ -``` +The repository includes: -Check the status of all pods: - -```bash -kubectl get pods -n shumai -``` - -Inspect the HorizontalPodAutoscaler: - -```bash -kubectl get hpa -n shumai -``` - -```text -NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS -shumai-transcode-hpa Deployment/shumai-transcode cpu: 10%/70% 1 5 1 -``` - -### Accessing the Dashboard & Storage - -In Kubernetes, services are created as internal `ClusterIP` services by default. To access the stack from your local development machine: - -1. **Forward the Web Server**: - - ```bash - kubectl port-forward -n shumai svc/shumai-server 3000:3000 - ``` - - Open **`http://localhost:3000`** in your browser. - -2. **Forward In-Cluster S3 Storage (Garage)**: - Shumai uses direct client-to-S3 presigned URLs for uploading and streaming media. `shumai-server` is configured with `AWS_PUBLIC_ENDPOINT_URL_S3: http://localhost:3900`. Forward port 3900 to allow your local browser to upload directly to Garage S3: - ```bash - kubectl port-forward -n shumai svc/garage 3900:3900 - ``` - -> [!NOTE] -> In production environments, configure an Ingress controller (e.g. `ingress-nginx` or AWS ALB) with a public domain or set `AWS_ENDPOINT_URL_S3` to an external cloud S3/R2 bucket. - -### How Autoscaling Operates - -1. **Scale-Up**: When users upload video assets, the `shumai-server` creates transcode workflow tasks and submits them to `transcode_queue` in PostgreSQL. As the active transcode worker utilizes CPU for FFmpeg encoding, CPU usage crosses the 70% threshold, triggering the HPA to scale up additional `shumai-transcode` pods (up to 5 pods). -2. **Per-Pod Executor Identity**: Each newly spawned pod uses `POD_NAME` as its DBOS executor identity. Pods poll `transcode_queue` in parallel, safely picking up and executing transcode jobs concurrently. -3. **Graceful Scale-Down & Drainage**: Worker pods configure `terminationGracePeriodSeconds: 300` and handle `SIGTERM` gracefully by draining active DBOS steps before termination, ensuring zero video proxy corruption during scale-down. - ---- - -## Deploying on AWS EKS with Graviton3 Spot Instances (`c7g.xlarge`) - -For production cloud deployments on Amazon Web Services (AWS), running transcode workers on **AWS Graviton3 (`c7g.xlarge`) Spot instances** provides the highest performance-to-cost ratio for CPU-intensive video processing. - -### Why Graviton3 Spot Instances? - -- **Dedicated Transcode Compute (`c7g.xlarge`)**: `c7g.xlarge` provides 4 dedicated ARM64 vCPUs and 8 GiB RAM, offering up to 25% better compute performance than x86-based equivalents for video transcoding. -- **Cost-Optimized System Nodes (`c7g.large`)**: The web server, PostgreSQL database, and Garage S3 run on a lightweight 2 vCPU / 4 GiB RAM (`c7g.large` Spot) node (~$0.029/hr). -- **Massive Cost Savings (60–70% off)**: In regions such as `us-east-1`, `c7g.xlarge` Spot instances cost approximately **$0.06/hour** (compared to ~$0.145/hour On-Demand). -- **Fault-Tolerant by Design**: Because DBOS workflow queues persist task states and execution steps directly in PostgreSQL, any spot interruption (2-minute warning) is handled cleanly: uncompleted jobs are simply recovered by surviving workers with zero data loss or stuck tasks. -- **Native Multi-Arch Images**: Official Docker images (`shumaione/shumai` and `shumaione/shumai-transcode`) provide native `linux/arm64` image manifests that run directly on AWS Graviton without emulation overhead. - -### Step 1: Provision the EKS Cluster with `eksctl` - -Save the following cluster definition as `k8s/eks-cluster.yaml`: - -```yaml -apiVersion: eksctl.io/v1alpha5 -kind: ClusterConfig - -metadata: - name: shumai-eks - region: us-east-1 - version: '1.31' - -iam: - withOIDC: true - -addons: - - name: aws-ebs-csi-driver - wellKnownPolicies: - ebsCSIController: true - -managedNodeGroups: - # General system workload: Web UI, REST API, DBOS PostgreSQL, and Garage S3 - - name: shumai-general-spot - instanceType: c7g.large # 2 vCPU, 4 GiB RAM (2c4g Spot, ~$0.029/hr) - spot: true - minSize: 1 - maxSize: 2 - desiredCapacity: 1 - amiFamily: AmazonLinux2023 - volumeSize: 50 - volumeType: gp3 - labels: - workload: general - iam: - withAddonPolicies: - autoScaler: true - ebs: true - - # Transcoding compute pool: High-CPU media processing - - name: shumai-transcode-spot - instanceType: c7g.xlarge # 4 vCPU, 8 GiB RAM (Graviton3 Spot, ~$0.06/hr) - spot: true - minSize: 1 - maxSize: 5 - desiredCapacity: 1 - amiFamily: AmazonLinux2023 - volumeSize: 50 - volumeType: gp3 - labels: - workload: transcode - iam: - withAddonPolicies: - autoScaler: true - ebs: true -``` - -Create the cluster using `eksctl`: - -```bash -eksctl create cluster -f k8s/eks-cluster.yaml -``` - -This sets up: - -1. An EKS control plane (Kubernetes 1.31) running in a dedicated VPC across multiple availability zones. -2. Two managed Spot node groups: a cost-efficient 2c4g node (`c7g.large`) for general system services and dedicated `c7g.xlarge` nodes for media transcoding. -3. IAM roles for service accounts (IRSA) and the AWS EBS CSI driver for persistent volume claims. - -### Step 2: Deploy the Shumai Stack & Public Services - -Deploy the manifests to your newly provisioned EKS cluster: - -```bash -kubectl apply -k k8s/ -``` - -Verify that all pods are running across your Graviton nodes: - -```bash -kubectl get nodes -L kubernetes.io/arch,node.kubernetes.io/instance-type,workload -kubectl get pods -n shumai -o wide -``` - -### Step 3: Accessing Public Services & Browser Uploads - -`k8s/shumai-server.yaml` and `k8s/garage.yaml` expose public AWS Load Balancer services (`type: LoadBalancer`). Retrieve the public external endpoints: - -```bash -kubectl get svc -n shumai -``` - -```text -NAME TYPE EXTERNAL-IP PORT(S) -shumai-server LoadBalancer k8s-shumai-xxx.us-east-1.elb.amazonaws.com 80:31234/TCP,3000:31235/TCP -garage-public LoadBalancer k8s-garage-xxx.us-east-1.elb.amazonaws.com 3900:31236/TCP -``` - -1. Configure `AWS_PUBLIC_ENDPOINT_URL_S3` on `shumai-server` to point to `http://:3900` so web browsers upload directly to the public Garage endpoint. -2. Open `http://` in your browser to access the Shumai dashboard. - -### Step 4: Autoscale Workers with HPA & Cluster Autoscaler - -To allow Kubernetes to automatically scale both transcode pods and underlying EC2 Spot nodes: - -1. **Deploy Kubernetes Cluster Autoscaler**: - -```bash -curl -s https://raw.githubusercontent.com/kubernetes/autoscaler/master/cluster-autoscaler/cloudprovider/aws/examples/cluster-autoscaler-autodiscover.yaml \ - | sed 's//shumai-eks/g' \ - | kubectl apply -f - -``` - -2. **Dedicated Node Allocation (1 Pod per `c7g.xlarge`)**: - `k8s/shumai-transcode.yaml` configures transcode worker requests to `3000m` CPU and limits to `3900m` (all 4 vCPUs). Because a `c7g.xlarge` instance has ~3.9 vCPUs allocatable, Kubernetes guarantees that **strictly one transcode worker runs per `c7g.xlarge` node**, allowing FFmpeg to utilize the full Graviton3 compute capacity without contention. - -3. **Autoscaling Flow**: - - When multiple videos are uploaded, HPA (`k8s/shumai-transcode-hpa.yaml`) detects high CPU usage and scales transcode worker pods. - - For pods that cannot fit on existing nodes, Cluster Autoscaler dynamically requests additional `c7g.xlarge` Spot instances from the AWS Auto Scaling Group. - - Once transcoding completes and the CPU load drops below 70% for 5 minutes (`stabilizationWindowSeconds: 300`), HPA scales down worker pods, and Cluster Autoscaler terminates unneeded EC2 Spot instances. +- [`eks/eks-cluster.yaml`](https://github.com/shumaiOne/shumai/blob/main/eks/eks-cluster.yaml): Complete `eksctl` ClusterConfig with compute tiering. +- [`eks/kustomization.yaml`](https://github.com/shumaiOne/shumai/blob/main/eks/kustomization.yaml): Single-command Kustomize deployment for all services. +- Detailed instructions for setting up public endpoints, automated Cluster Autoscaler, and zero-downtime graceful shutdown. diff --git a/eks/README.md b/eks/README.md new file mode 100644 index 00000000..6286a31b --- /dev/null +++ b/eks/README.md @@ -0,0 +1,234 @@ +# Shumai on AWS EKS with Graviton3 Spot & Autoscaling + +This directory contains a complete, production-ready Kubernetes deployment example demonstrating how to run Shumai on **Amazon Elastic Kubernetes Service (AWS EKS)** with horizontal autoscaling for compute-heavy media processing. + +--- + +## Architecture Overview + +```text + [ User / Internet ] + │ + ┌────────────────────┴────────────────────┐ + │ (Port 80/3000) │ (Port 3900) + ▼ ▼ + ┌───────────────────────┐ ┌───────────────────────┐ + │ shumai-server (ELB) │ │ garage-public (ELB) │ + └───────────┬───────────┘ └───────────┬───────────┘ + │ │ Direct Browser Uploads + │ ▼ (Presigned URLs) +┌───────────────────┼─────────────────────────────────────────────────────────────────┐ +│ General Workload Node (c7g.large Spot, ~$0.029/hr) │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────┐ DBOS Tasks ┌───────────────────────────┐ │ +│ │ shumai-server ├─────────────────►│ shumai-postgres │ │ +│ │ (SHUMAI_WORKERS=agent)│ (transcode_queue)│ (pgvector:pg18) │ │ +│ └───────────┬───────────┘ └─────────────┬─────────────┘ │ +│ │ │ │ +│ │ │ Task Polling │ +│ ▼ ▼ │ +│ ┌───────────────────────┐ ┌───────────────────────────┐ │ +│ │ garage-s3 │◄─────────────────┤ shumai-transcode │ │ +│ │ (dxflrs/garage) │ Fetch Source / │ (Worker Pod 1) │ │ +│ └───────────────────────┘ Write Proxies └───────────────────────────┘ │ +└────────────────────────────────────────────────────────────────┬────────────────────┘ + │ HPA Target: 70% CPU + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ Transcode Compute Pool (c7g.xlarge Graviton3 Spot, ~$0.06/hr, 1 Pod per Node) │ +│ │ +│ ┌──────────────────────────┐ ┌──────────────────────────┐ ┌────────────────────┐ │ +│ │ shumai-transcode │ │ shumai-transcode │ │ shumai-transcode │ │ +│ │ (Worker Pod 2) │ │ (Worker Pod 3) │ │ (Worker Pod N) │ │ +│ └──────────────────────────┘ └──────────────────────────┘ └────────────────────┘ │ +│ ▲ ▲ ▲ │ +│ │ │ │ │ +│ ┌────────┴─────────────────┐ ┌─────────┴────────────────┐ ┌─────────┴──────────┐ │ +│ │ Node: c7g.xlarge (Spot) │ │ Node: c7g.xlarge (Spot) │ │Node: c7g.xlarge │ │ +│ └──────────────────────────┘ └──────────────────────────┘ └────────────────────┘ │ +│ │ +│ Cluster Autoscaler: Dynamically provisions / terminates c7g.xlarge nodes │ +└─────────────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Core Design Principles + +### 1. Compute Tiering & Why Graviton3 (`c7g.xlarge`) + +Media transcoding with FFmpeg is one of the most CPU-intensive workloads in modern web applications. To achieve maximum throughput at minimum cost, this deployment separates system services from media encoding: + +- **General System Node (`shumai-general-spot`)**: A single 2 vCPU / 4 GiB RAM (`c7g.large` Spot) node (~$0.029/hr) runs the Web UI, API, PostgreSQL, and Garage S3. +- **Dedicated Transcode Pool (`shumai-transcode-spot`)**: High-performance 4 vCPU / 8 GiB RAM (`c7g.xlarge` Spot) instances dedicated exclusively to media encoding. + +**Why choose AWS Graviton3 (`c7g.xlarge`)?** +AWS Graviton3 ARM64 processors feature dedicated Neoverse V1 cores with native FP16 and SVE (Scalable Vector Extension) vector units. As detailed in AWS's benchmark study, [Optimized Video Encoding with FFmpeg on AWS Graviton Processors](https://aws.amazon.com/cn/blogs/opensource/optimized-video-encoding-with-ffmpeg-on-aws-graviton-processors/), Graviton processors deliver **up to 25–40% better performance** and higher frames-per-second per dollar compared to x86 equivalents. Coupled with AWS EC2 Spot instances, `c7g.xlarge` costs only **~$0.06/hour** (a ~60% discount over On-Demand). + +### 2. In-Cluster S3 vs. Native Amazon S3 + +> [!NOTE] +> **Why Garage is included in this example**: +> We include **Garage S3** (`dxflrs/garage`) on EBS gp3 to demonstrate a **100% self-contained, fully self-hosted deployment** that boots without requiring an external cloud storage account or pre-existing S3 buckets. + +> [!TIP] +> **Production Recommendation**: +> If you are deploying on AWS, you should consider using **native Amazon S3 directly** (e.g. by setting `S3_BUCKET: my-prod-bucket`). Real Amazon S3 provides virtually infinite capacity, 11 9s durability, global availability, and eliminates the operational overhead of managing in-cluster storage volumes. + +When running Garage in-cluster, Shumai utilizes **Split-Horizon S3 Resolution**: +- **Internal Traffic (`AWS_ENDPOINT_URL_S3`)**: Points to `http://garage.shumai.svc.cluster.local:3900`. Backend server and worker pods stream source files and upload transcoded HLS chunks over private cluster networking with **zero AWS data transfer fees** and microsecond latency. +- **Public Client Traffic (`AWS_PUBLIC_ENDPOINT_URL_S3`)**: Points to the public LoadBalancer (`http://:3900`) for generating presigned upload/download URLs so end-user browsers can stream and upload files directly. + +### 3. Task Orchestration via DBOS Transact + +All video and document transcoding jobs are enqueued to `transcode_queue` inside PostgreSQL via **DBOS Transact**. Transcode workers are completely stateless and consume jobs from the queue. Each worker pod uses the Kubernetes Downward API (`POD_NAME`) to obtain a unique, collision-free executor ID. + +--- + +## Autoscaling Mechanics + +Autoscaling operates across two coordinated layers: + +```mermaid +flowchart LR + Upload[Video Uploads Spike] --> HPA[HPA detects CPU > 70%] + HPA --> ScalePods[Scale Pods 1 to 5] + ScalePods --> Pending[Pods Enter Pending: 3000m CPU needed] + Pending --> CA[Cluster Autoscaler launches c7g.xlarge Spot nodes] + CA --> Ready[1 Pod scheduled per dedicated c7g.xlarge Node] +``` + +1. **Horizontal Pod Autoscaler (HPA)**: + - Configured in [`shumai-transcode-hpa.yaml`](./shumai-transcode-hpa.yaml) targeting **70% CPU utilization** of the pod's `3000m` CPU request (= 2.1 vCPUs). + - When a video transcode starts, FFmpeg consumes ~3.5 cores, immediately exceeding 70% and prompting HPA to scale out worker pods (up to 5 replicas). +2. **1:1 Dedicated Pod-to-Node Allocation**: + - In [`shumai-transcode.yaml`](./shumai-transcode.yaml), worker pods request `cpu: 3000m` and `memory: 4Gi` with limits at `cpu: 3900m` and `memory: 6Gi`. + - Because a `c7g.xlarge` instance has `3920m` allocatable CPU, **strictly 1 transcode pod can fit per node**, giving FFmpeg unrestricted access to all 4 physical cores without CPU throttling. + - Additional pods enter `Pending` state, which immediately triggers the **Kubernetes Cluster Autoscaler** to scale up the AWS Auto Scaling Group (`shumai-transcode-spot`). +3. **Graceful Scale-Down & Task Safety**: + - **5-Minute HPA Stabilization Window** (`stabilizationWindowSeconds: 300`): Once the queue is clear and CPU drops to 0%, HPA holds replicas for 5 minutes to avoid pod thrashing if new uploads arrive. + - **5-Minute Termination Grace Period** (`terminationGracePeriodSeconds: 300`): When Kubernetes terminates a worker, it sends `SIGTERM`. The worker stops taking new jobs, drains the active FFmpeg transcode step, uploads proxies to S3, and exits cleanly. + - **10-Minute Node Cooldown**: Cluster Autoscaler waits for idle nodes to be unneeded for 10 minutes (`scale-down-unneeded-time=10m`) before cordoning, draining, and terminating the EC2 Spot instance. + +--- + +## Step-by-Step Deployment Guide + +### Prerequisites + +- [AWS CLI](https://aws.amazon.com/cli/) installed and configured (`aws configure`). +- [`eksctl`](https://eksctl.io/) installed. +- [`kubectl`](https://kubernetes.io/docs/tasks/tools/) installed. + +### Step 1: Provision the EKS Cluster + +Create the cluster using the declarative [`eks/eks-cluster.yaml`](./eks-cluster.yaml) configuration: + +```bash +eksctl create cluster -f eks/eks-cluster.yaml +``` + +This provisions: +- An EKS 1.31 control plane in a dedicated VPC across multiple AZs. +- `shumai-general-spot`: 1x `c7g.large` Spot instance (labeled `workload: general`). +- `shumai-transcode-spot`: Autoscaling `c7g.xlarge` Spot instances (min: 1, max: 5, labeled `workload: transcode`). +- AWS EBS CSI Driver with IAM OIDC roles. + +### Step 2: Deploy the Shumai Stack + +Deploy all components with Kustomize: + +```bash +kubectl apply -k eks/ +``` + +Verify that all initial pods reach `Running` state: + +```bash +kubectl get pods -n shumai -o wide +``` + +### Step 3: Configure Public Access & S3 Endpoint + +Retrieve the external LoadBalancer hostnames created by AWS: + +```bash +kubectl get svc -n shumai +``` + +```text +NAME TYPE EXTERNAL-IP PORT(S) +shumai-server LoadBalancer k8s-shumai-xxx.us-east-1.elb.amazonaws.com 80:31234/TCP,3000:31235/TCP +garage-public LoadBalancer k8s-garage-xxx.us-east-1.elb.amazonaws.com 3900:31236/TCP +``` + +#### Option A: Quick Testing (Automated 1-Liner) +Inject the public Garage ELB hostname into `shumai-server`: + +```bash +GARAGE_ELB=$(kubectl get svc garage-public -n shumai -o jsonpath='{.status.loadBalancer.ingress[0].hostname}') +kubectl set env deployment/shumai-server -n shumai AWS_PUBLIC_ENDPOINT_URL_S3="http://${GARAGE_ELB}:3900" +``` + +#### Option B: Production with Custom Domains +In production, point DNS records (e.g. Route 53) to your load balancers: +- Web App: `https://shumai.mycompany.com` +- S3 Storage: `https://s3.mycompany.com` + +Set `AWS_PUBLIC_ENDPOINT_URL_S3: https://s3.mycompany.com` in [`eks/config.yaml`](./config.yaml) and apply once. + +#### Option C: Native Amazon S3 +If using real AWS S3, set `STORAGE_BACKEND: s3`, provide `S3_BUCKET`, and omit `AWS_PUBLIC_ENDPOINT_URL_S3` (native AWS S3 endpoints resolve globally). + +### Step 4: Deploy Kubernetes Cluster Autoscaler + +Deploy the official Cluster Autoscaler to enable automated node provisioning: + +```bash +curl -s https://raw.githubusercontent.com/kubernetes/autoscaler/master/cluster-autoscaler/cloudprovider/aws/examples/cluster-autoscaler-autodiscover.yaml \ + | sed 's//shumai-eks/g' \ + | kubectl apply -f - + +# Pin autoscaler to the general workload node +kubectl patch deployment cluster-autoscaler -n kube-system -p '{"spec":{"template":{"spec":{"nodeSelector":{"workload":"general"}}}}}' +``` + +### Step 5: Test Horizontal Autoscaling + +1. Open `http://` in your browser and log in with your credentials. +2. Upload a batch of 10–20 video files simultaneously. +3. Watch the workers scale up horizontally: + ```bash + kubectl get hpa -n shumai -w + kubectl get pods -n shumai -l app=shumai-transcode -o wide + kubectl get nodes -L node.kubernetes.io/instance-type,workload + ``` +4. Observe that each worker consumes ~3 vCPUs on its dedicated `c7g.xlarge` instance. +5. Once all jobs complete, observe HPA scaling back down to 1 pod and Cluster Autoscaler terminating idle EC2 Spot instances. + +### Step 6: Cluster Teardown & Cost Cleanup + +When you are finished testing, delete all resources to prevent ongoing cloud charges: + +```bash +# 1. Delete Kubernetes namespace to release ELB load balancers and EBS volumes +kubectl delete namespace shumai + +# 2. Delete the EKS cluster and CloudFormation stacks +eksctl delete cluster -f eks/eks-cluster.yaml --wait +``` + +--- + +## Portability to Generic Kubernetes + +While this directory is configured for AWS EKS, the exact same architecture applies directly to any Kubernetes environment: + +- **Google Kubernetes Engine (GKE)**: Use `tau T2A` ARM64 instances for transcode workers and standard persistent disks (`pd-balanced`). +- **Azure Kubernetes Service (AKS)**: Use `Dpsv5` ARM64 Spot node pools. +- **Local (Minikube / Docker Desktop / Kind)**: Use the same manifests without node selectors or Cluster Autoscaler. Access services via `kubectl port-forward`: + ```bash + kubectl port-forward -n shumai svc/shumai-server 3000:3000 + kubectl port-forward -n shumai svc/garage 3900:3900 + ``` diff --git a/k8s/config.yaml b/eks/config.yaml similarity index 100% rename from k8s/config.yaml rename to eks/config.yaml diff --git a/k8s/eks-cluster.yaml b/eks/eks-cluster.yaml similarity index 100% rename from k8s/eks-cluster.yaml rename to eks/eks-cluster.yaml diff --git a/k8s/garage.yaml b/eks/garage.yaml similarity index 100% rename from k8s/garage.yaml rename to eks/garage.yaml diff --git a/k8s/kustomization.yaml b/eks/kustomization.yaml similarity index 100% rename from k8s/kustomization.yaml rename to eks/kustomization.yaml diff --git a/k8s/namespace.yaml b/eks/namespace.yaml similarity index 100% rename from k8s/namespace.yaml rename to eks/namespace.yaml diff --git a/k8s/postgres.yaml b/eks/postgres.yaml similarity index 100% rename from k8s/postgres.yaml rename to eks/postgres.yaml diff --git a/k8s/shumai-server.yaml b/eks/shumai-server.yaml similarity index 100% rename from k8s/shumai-server.yaml rename to eks/shumai-server.yaml diff --git a/k8s/shumai-transcode-hpa.yaml b/eks/shumai-transcode-hpa.yaml similarity index 100% rename from k8s/shumai-transcode-hpa.yaml rename to eks/shumai-transcode-hpa.yaml diff --git a/k8s/shumai-transcode.yaml b/eks/shumai-transcode.yaml similarity index 100% rename from k8s/shumai-transcode.yaml rename to eks/shumai-transcode.yaml diff --git a/k8s/README.md b/k8s/README.md deleted file mode 100644 index d1a67674..00000000 --- a/k8s/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Shumai Kubernetes Deployment & Autoscaling Example - -This directory contains a complete, production-ready Kubernetes example demonstrating how to run Shumai in a decoupled, horizontally scalable architecture powered by **DBOS Transact** and **Garage S3** (`dxflrs/garage`). - ---- - -## Architecture Overview - -```text - [ User / Ingress ] - │ - ▼ (Port 3000) - ┌───────────────────────────────┐ - │ shumai-server (Deployment) │ - │ SHUMAI_WORKERS=agent │ - └───────┬───────────────┬───────┘ - │ │ - DBOS Task Submissions │ │ Direct S3 Uploads/Reads - (Queue: transcode_queue)│ │ - ▼ ▼ - ┌──────────────────────┐ ┌───────────────┐ - │ shumai-postgres │ │ garage-s3 │ - │ (pgvector:pg18) │ │ (dxflrs/garage)│ - └──────────┬───────────┘ └───────▲───────┘ - │ │ - DBOS Queue │ │ Fetch source video - Polling │ │ Store transcoded proxies - ▼ │ - ┌──────────────────────┐ │ - │ shumai-transcode ├─────────┘ - │ (1..5 Autoscaled Pods) - └──────────────────────┘ - ▲ - │ CPU Utilization Target (70%) - ┌──────────────────────┐ - │ shumai-transcode-hpa │ - │ (min: 1, max: 5) │ - └──────────────────────┘ -``` - -1. **`shumai-server`**: Serves the Web dashboard and REST API, while processing agent workflows. It sets `SHUMAI_WORKERS=agent` so that all video and media transcoding tasks are delegated directly to the `transcode_queue` in PostgreSQL. -2. **`shumai-transcode`**: Dedicated stateless worker pool consuming tasks from `transcode_queue`. Each replica uses the Kubernetes Downward API to set `POD_NAME` for unique, collision-free DBOS executor identity. -3. **`garage`**: Lightweight distributed S3-compatible object storage (`dxflrs/garage`) providing high-performance shared storage for original and transcoded media files without requiring external cloud storage. -4. **`shumai-postgres`**: PostgreSQL database with `pgvector:pg18` running both application persistence and DBOS workflow queues. -5. **`shumai-transcode-hpa`**: `HorizontalPodAutoscaler` (`autoscaling/v2`) that monitors transcode worker CPU utilization and scales the pool between **1 and 5 replicas**. - ---- - -## Quickstart: Deploy to Kubernetes - -### Prerequisites -- A Kubernetes cluster (e.g. Docker Desktop, Minikube, Kind, or managed cloud Kubernetes). -- `kubectl` configured with cluster access. -- `metrics-server` installed in your cluster (required by HPA to read CPU metrics). - -### 1. Deploy the Entire Stack -Run a single command using Kustomize: - -```bash -kubectl apply -k k8s/ -``` - -### 2. Monitor Pod Status -Watch until all components are running and initialized: - -```bash -kubectl get pods -n shumai -w -``` - -Expected output: -```text -NAME READY STATUS RESTARTS AGE -garage-0 1/1 Running 0 1m -garage-init-xxxxx 0/1 Completed 0 45s -shumai-postgres-0 1/1 Running 0 1m -shumai-server-xxxxxxxxxx-xxxxx 1/1 Running 0 1m -shumai-transcode-yyyyyyyyyy-yyyyy 1/1 Running 0 1m -``` - -### 3. Check Autoscaling Status -Inspect the HorizontalPodAutoscaler: - -```bash -kubectl get hpa -n shumai -``` - -You should see: -```text -NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE -shumai-transcode-hpa Deployment/shumai-transcode 0%/70% 1 5 1 1m -``` - -### 4. Access the Dashboard & S3 Storage - -In Kubernetes, the services are created as internal `ClusterIP` services by default. To interact with the stack from your local machine: - -#### Step A: Port-forward the Web Server -Forward port 3000 to access the web application: -```bash -kubectl port-forward -n shumai svc/shumai-server 3000:3000 -``` -Open your browser to **`http://localhost:3000`**. - -#### Step B: Port-forward In-Cluster S3 Storage (Garage) -Shumai generates direct client-to-S3 presigned URLs configured via `AWS_PUBLIC_ENDPOINT_URL_S3` (`http://localhost:3900`). To allow your browser to upload and stream media files directly: - -```bash -kubectl port-forward -n shumai svc/garage 3900:3900 -``` - -> [!NOTE] -> **AWS EKS Deployment with Graviton3 Spot Instances**: For production deployments on AWS with dedicated high-performance ARM64 transcoding, see [`k8s/eks-cluster.yaml`](file:///Users/yiling/Projects/shumai/k8s/eks-cluster.yaml) and the [Distributed Deployment Guide](file:///Users/yiling/Projects/shumai/docs/configuration/distributed.mdx#deploying-on-aws-eks-with-graviton3-spot-instances-c7gxlarge). It provisions a lightweight 2c4g node for general services and auto-scales dedicated `c7g.xlarge` Spot instances for media processing. - ---- - -## Testing Transcoding & Horizontal Autoscaling - -1. Upload one or more video files in the Shumai Web UI. -2. Observe the `shumai-transcode` worker pod picking up the transcode tasks in its logs: - ```bash - kubectl logs -n shumai -l app=shumai-transcode -f - ``` -3. When multiple heavy video transcoding jobs run concurrently, CPU utilization increases past 70%, triggering the HPA to scale up additional worker pods: - ```bash - kubectl get hpa -n shumai -w - ``` -4. Once transcoding completes, the HPA will hold replicas for a 300-second stabilization window before cleanly scaling back down to 1 pod.