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.
Media transcoding with FFmpeg is one of the most CPU-intensive workloads in modern web applications. To ensure rock-solid stability for persistent data while minimizing transcoding costs, this deployment strictly separates system services from media encoding:
- **General System Node (`shumai-general`)**: A single 2 vCPU / 4 GiB RAM (`c9g.large`**On-Demand**) node (~$0.087/hr) hosts the Web UI, API server, PostgreSQL database, and Garage S3.
> [!IMPORTANT]
> **Why On-Demand for Core Services?**
> Spot instances are subject to involuntary AWS reclamation (interruption). Running stateful services (PostgreSQL, local S3 storage) and the primary user-facing API on an On-Demand instance guarantees that the database and storage layers are never killed, evicted, or subject to abrupt downtime.
- **Dedicated Transcode Pool (`shumai-transcode-spot`)**: High-performance 4 vCPU / 8 GiB RAM Graviton Spot instances (`c9g.xlarge` primary, with `c8g.xlarge` fallback pools) dedicated exclusively to media encoding.
AWS Graviton5 is AWS's fifth-generation custom ARM64 processor, built on the 6th-generation Nitro system with sustained 3.3 GHz clock speeds, high-speed DDR5 memory (8800 MT/s), and 5x more L3 cache. As demonstrated in AWS's video encoding benchmarks (see [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 exceptional performance and frames-per-second per dollar for media workloads. Graviton5 further pushes compute performance by up to 25% per vCPU. Coupled with AWS EC2 Spot instances, `c9g.xlarge` costs only **~$0.08/hour** (a massive discount over On-Demand).
> 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://<garage-public-elb>: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.
### 4. What Happens If Transcode Spot Nodes Are Interrupted or Killed?
Because the transcode workers are completely stateless and coordinated via **DBOS Transact** against PostgreSQL on the On-Demand node:
1.**State Isolation**:
PostgreSQL, EBS persistent volume claims, the Web UI, and S3 storage live on the On-Demand node and are **never terminated** during Spot interruptions.
When AWS reclaims a Spot instance, it issues a 2-minute notice. Kubernetes drains the node and sends `SIGTERM` to the worker pod. With `terminationGracePeriodSeconds: 300`, the worker finishes any encoding step currently near completion, uploads the result to S3, and exits cleanly.
3.**Automatic Step Recovery via DBOS**:
If an instance is terminated abruptly mid-encode, **zero data or tasks are lost**. The video source file remains safe in S3. DBOS workflow step states are durably tracked in PostgreSQL; uncompleted tasks are detected by surviving or newly launched workers and automatically re-executed from their last durable checkpoint.
4.**Spot Capacity Pool Diversification**:
[`eks/eks-cluster.yaml`](./eks-cluster.yaml) configures `instanceTypes: [c9g.xlarge, c8g.xlarge]`. If AWS temporarily exhausts Graviton5 (`c9g.xlarge`) Spot capacity in an Availability Zone, the Auto Scaling Group immediately falls back to Graviton4 (`c8g.xlarge`) Spot capacity. All three families share the same 4 vCPU / 8 GiB RAM profile and ARM64 architecture.
5.**What If All Spot Nodes Are Killed Simultaneously?**
- Transcode worker pods enter `Pending` state (`Insufficient cpu`).
- All newly submitted transcode jobs queue safely inside PostgreSQL on the On-Demand node. No user uploads or jobs are dropped.
- The **Cluster Autoscaler** detects the `Pending` pods and continuously requests new EC2 Spot instances from AWS.
- As soon as Spot capacity becomes available (typically within 1–2 minutes), new nodes launch, pods schedule to `Running`, and workers resume draining the queue.
- 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 `c9g.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`).
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:
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`: