01วิเคราะห์โจทย์

โจทย์มีคำสำคัญ 4 คำ: ไฟล์ไม่เกิน 2GB (upload path ต้องไม่ผ่าน API server), งานละ 5–30 นาที (งานยาวกว่าที่ request/response รับได้ ต้องเป็น async job), worker ตายกลางทางได้ (at-least-once + lease + idempotency) และ อัปโหลดพร้อมกันจำนวนมาก (queue เป็น buffer + autoscale) บวกกับ progress ที่ผู้ใช้ต้องเห็น ข้อกำหนดท้ายโจทย์บอกชัดว่างาน "ต้องไม่หายและไม่ถูกทำซ้ำจนผลเสีย" ซึ่งก็คือ invariant ของโจทย์นี้

invariant.txt
สำหรับทุก transcode job (video_id, rendition):
  1) ไม่หาย: ต้องจบที่ DONE หรือ FAILED เสมอ แม้ worker ตายกลางทาง
  2) ไม่เสียซ้ำ: มีผลลัพธ์ที่ถูก commit ได้ชุดเดียว (ของ attempt ที่ชนะ)
สำหรับทุก video:
  3) READY ก็ต่อเมื่อทุก rendition ที่ต้องทำเป็น DONE และ publish ครั้งเดียว

-> สถานะ job บังคับที่ PostgreSQL (attempt = fencing token)
-> SQS รับประกันแค่ "ส่งอย่างน้อยหนึ่งครั้ง" จึงไม่ใช่ผู้ตัดสินว่าใครทำงานชิ้นนี้
FUNCTIONAL
  • อัปโหลดวิดีโอไม่เกิน 2GB และ resume ได้เมื่อเน็ตหลุด
  • Transcode เป็น 4 ความละเอียด (1080p/720p/480p/360p) แบบ HLS
  • ผู้ใช้เห็น progress แบบ near real-time และสถานะสุดท้าย
  • เล่นวิดีโอผ่าน CDN เมื่อพร้อม
NON-FUNCTIONAL
  • งานไม่หาย แม้ worker ตาย (at-least-once + recovery ≤ 3 นาที)
  • ทำซ้ำได้โดยผลไม่เสีย (idempotent output, publish ครั้งเดียว)
  • รับ burst ได้: คิวดูดซับ, worker scale ตาม backlog
  • ต้นทุน compute คุมได้ (เพดาน + spot) และ observe ได้

Capacity: สมมติ 10,000 uploads/วัน เฉลี่ย 500MB (ยาว ~10 นาที) peak hour 3 เท่าของค่าเฉลี่ย ≈ 1,250 uploads/ชม. ขาเข้าตอน peak ≈ 1,250 × 0.5GB / 3,600s ≈ 174MB/s (~1.4 Gbps) ถ้าผ่าน API จะกลายเป็นคอขวดทันที จึงต้องใช้ presigned URL ส่วน compute: 1 วิดีโอใช้ประมาณ 25 + 15 + 8 + 5 ≈ 50 worker-minutes ทั้งวันจึงเท่ากับ 500,000 worker-minutes ≈ 347 worker ทำงานตลอด 24 ชม. แต่ตอน peak งานเข้ามา 62,500 worker-minutes/ชม. ต้องใช้ประมาณ 1,040 worker ถึงจะไม่มี backlog ตัวเลขนี้บอกว่าต้อง autoscale และต้องตัดสินใจว่าจะ ตั้งเพดาน (เช่น 800) แล้วให้คิวรับส่วนเกิน หรือจะจ่ายเพิ่มเพื่อ latency ส่วน storage: source 5TB/วัน + rendition ~7.5TB/วัน (รวม bitrate ~10 Mbps × 10 นาที ≈ 750MB) ≈ 375TB/เดือน จึงต้องมี lifecycle policy

02ภาพรวมแนวทาง

ทุกแนวทางใช้ แกนร่วม ชุดเดียวกัน (presigned upload, job table ที่มี attempt, idempotent output, progress ผ่าน Redis) สิ่งที่ต่างกันคือ ใครเป็นคนจำว่างานไหนค้างอยู่และต้อง retry และขนาดของหน่วยงานที่เสียเมื่อ worker ตาย

เกณฑ์A · Work QueueB · OrchestratorC · Chunked
ใครรับประกันว่างานไม่หาย

SQS visibility timeout + heartbeat + lease ใน PostgreSQL

Event history ของ Temporal + HeartbeatTimeout + RetryPolicy

เหมือน A แต่ task เล็กระดับ chunk

งานที่เสียเมื่อ worker ตาย

ทั้ง rendition (สูงสุด ~30 นาที)

ทั้ง activity (ถ้าไม่ทำ checkpoint)

แค่ chunk เดียว (~1 นาที)

เวลาจนดูได้

เท่างานที่ยาวที่สุด 5–30 นาที (4 rendition ขนานกัน)

เท่า A

ไม่กี่นาที เมื่อมี worker ว่างพอ

Fan-out / fan-in

เขียนเอง: UNIQUE + counter ใน DB

เขียนเป็นโค้ด workflow (Future) พร้อม cancel

2 ชั้น: chunk → rendition → video

Component เพิ่ม

SQS + DLQ (managed)

Temporal cluster หรือ Temporal Cloud / Step Functions

Split/assemble job + chunk table + audio job

เหมาะกับ

คำตอบหลักในห้องสอบ และ pipeline ขั้นตอนไม่มาก

Pipeline หลายขั้น มี human review หรือ SLA ต่อขั้น

วิดีโอยาวมาก หรือ SLA จนดูได้เป็นนาที

อยากเห็นภาพรวมก่อนว่าไฟล์ที่ส่งหน้าตาเป็นอย่างไร ให้ข้ามไปดู ไฟล์คำตอบ system-design.md ฉบับเต็ม ↓

03แกนร่วมทุกแนวทาง

ส่วนนี้ต้องมีในทุกแนวทาง เพราะ upload, สถานะของ job, การเขียนผลลัพธ์แบบ idempotent และ progress ไม่ขึ้นกับว่าใครเป็นคนสั่งงาน

Upload: presigned multipart ตรงเข้า S3

API ทำแค่ 2 อย่าง: ออก presigned URL และปิดงานเมื่อ upload เสร็จ ไฟล์วิ่งจาก client เข้า S3 โดยตรง API server จึงไม่ต้องรับ 1.4 Gbps ตอน peak และใช้ multipart ให้ resume ทีละ part ได้ จุดที่มักพลาดมี 3 ข้อ:

  1. 1
    ห้ามเชื่อขนาดที่ client บอก

    ตรวจซ้ำด้วย HeadObject หลัง complete ถ้าเกิน 2GB ให้ mark FAILED

  2. 2
    Complete ต้อง idempotent

    Client timeout แล้วกดซ้ำ ต้องได้ผลเดิม (เช็ค status และรองรับ NoSuchUpload)

  3. 3
    เก็บขยะ

    Lifecycle rule AbortIncompleteMultipartUpload ไม่งั้น part ที่ค้างยังถูกคิดค่า storage

upload.go
// Upload ตรงเข้า S3 ด้วย multipart + presigned URL: ไฟล์ 2GB ไม่ผ่าน API server เลย
package upload

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/google/uuid"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

const (
	maxSize  = 2 << 30          // 2 GiB
	partSize = 64 << 20         // 64 MiB → ไฟล์ 2GB = 32 part (S3: ขั้นต่ำ 5 MiB ยกเว้น part สุดท้าย)
	urlTTL   = 1 * time.Hour
)

var ErrTooLarge = errors.New("file exceeds 2GB")

type PresignedPart struct {
	PartNumber int32  `json:"partNumber"`
	URL        string `json:"url"`
}

type Handler struct {
	db      *pgxpool.Pool
	s3      *s3.Client
	presign *s3.PresignClient // s3.NewPresignClient(s3Client)
	bucket  string
}

func (h *Handler) Create(ctx context.Context, ownerID uuid.UUID, size int64, contentType string) (uuid.UUID, []PresignedPart, error) {
	if size <= 0 || size > maxSize {
		return uuid.Nil, nil, ErrTooLarge // ด่านแรก: เชื่อ client ไม่ได้ ต้องตรวจซ้ำตอน complete
	}
	videoID := uuid.New()
	key := fmt.Sprintf("raw/%s/source", videoID)

	mpu, err := h.s3.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{
		Bucket:      aws.String(h.bucket),
		Key:         aws.String(key),
		ContentType: aws.String(contentType),
	})
	if err != nil {
		return uuid.Nil, nil, err
	}
	if _, err := h.db.Exec(ctx, `
		INSERT INTO videos (id, owner_id, status, source_key, s3_upload_id)
		VALUES ($1, $2, 'UPLOADING', $3, $4)`,
		videoID, ownerID, key, aws.ToString(mpu.UploadId)); err != nil {
		return uuid.Nil, nil, err
	}

	n := int32((size + partSize - 1) / partSize)
	parts := make([]PresignedPart, 0, n)
	for p := int32(1); p <= n; p++ {
		req, err := h.presign.PresignUploadPart(ctx, &s3.UploadPartInput{
			Bucket:     aws.String(h.bucket),
			Key:        aws.String(key),
			UploadId:   mpu.UploadId,
			PartNumber: aws.Int32(p),
		}, s3.WithPresignExpires(urlTTL))
		if err != nil {
			return uuid.Nil, nil, err
		}
		parts = append(parts, PresignedPart{PartNumber: p, URL: req.URL})
	}
	return videoID, parts, nil
}

// Complete เรียกซ้ำได้ (idempotent): client timeout แล้วกดใหม่ต้องไม่พัง
func (h *Handler) Complete(ctx context.Context, ownerID, videoID uuid.UUID, parts []types.CompletedPart) error {
	var key, uploadID, status string
	if err := h.db.QueryRow(ctx, `
		SELECT source_key, s3_upload_id, status FROM videos
		WHERE id = $1 AND owner_id = $2`, videoID, ownerID).Scan(&key, &uploadID, &status); err != nil {
		return err
	}
	if status != "UPLOADING" {
		return nil // complete ไปแล้ว → ตอบเหมือนเดิม
	}

	_, err := h.s3.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
		Bucket:          aws.String(h.bucket),
		Key:             aws.String(key),
		UploadId:        aws.String(uploadID),
		MultipartUpload: &types.CompletedMultipartUpload{Parts: parts},
	})
	var noUpload *types.NoSuchUpload
	if err != nil && !errors.As(err, &noUpload) { // NoSuchUpload = ครั้งก่อน complete สำเร็จแล้ว
		return err
	}

	// ตรวจขนาดจริงจาก S3 ไม่ใช่จากที่ client บอก
	head, err := h.s3.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(h.bucket), Key: aws.String(key)})
	if err != nil {
		return err
	}
	size := aws.ToInt64(head.ContentLength)

	return pgx.BeginFunc(ctx, h.db, func(tx pgx.Tx) error {
		next := "UPLOADED"
		if size > maxSize {
			next = "FAILED" // ลบ object ทิ้งด้วย cleanup job
		}
		tag, err := tx.Exec(ctx, `
			UPDATE videos SET status = $2, size_bytes = $3, updated_at = now()
			WHERE id = $1 AND status = 'UPLOADING'`, videoID, next, size)
		if err != nil || tag.RowsAffected() == 0 || next == "FAILED" {
			return err
		}
		// ส่งต่อให้ probe worker ผ่าน outbox (ไม่มี dual write ระหว่าง DB กับ SQS)
		_, err = tx.Exec(ctx, `
			INSERT INTO outbox (aggregate_id, event_type, payload)
			VALUES ($1, 'VideoUploaded', jsonb_build_object('videoId', $1::text))`, videoID)
		return err
	})
}
upload-client.ts
type PresignedPart = { partNumber: number; url: string };
type CreateUploadResponse = {
  videoId: string;
  partSize: number;
  parts: PresignedPart[];
};

const MAX_SIZE = 2 * 1024 ** 3;
const CONCURRENCY = 4; // อัปโหลดพร้อมกัน 4 part

export async function uploadVideo(
  file: File,
  onProgress: (pct: number) => void,
): Promise<string> {
  if (file.size > MAX_SIZE) throw new Error("ไฟล์ใหญ่เกิน 2GB");

  const { videoId, partSize, parts } = await postJson<CreateUploadResponse>(
    "/videos",
    { filename: file.name, size: file.size, contentType: file.type },
    crypto.randomUUID(), // Idempotency-Key: กดซ้ำไม่สร้าง video ซ้ำ
  );

  const done: { partNumber: number; etag: string }[] = [];
  let cursor = 0;
  let uploaded = 0;

  async function uploadNext(): Promise<void> {
    while (cursor < parts.length) {
      const part = parts[cursor++]!;
      const start = (part.partNumber - 1) * partSize;
      const blob = file.slice(start, Math.min(start + partSize, file.size));
      const etag = await putPartWithRetry(part.url, blob);
      done.push({ partNumber: part.partNumber, etag });
      uploaded += blob.size;
      onProgress(Math.round((uploaded / file.size) * 100));
    }
  }
  await Promise.all(Array.from({ length: CONCURRENCY }, uploadNext));

  done.sort((a, b) => a.partNumber - b.partNumber); // S3 ต้องการเรียงตาม partNumber
  await postJson(`/videos/${videoId}/complete`, { parts: done });
  return videoId;
}

// เน็ตหลุดกลางทาง → retry เฉพาะ part นั้น ไม่ต้องเริ่ม 2GB ใหม่
async function putPartWithRetry(url: string, blob: Blob): Promise<string> {
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const res = await fetch(url, { method: "PUT", body: blob });
      const etag = res.headers.get("ETag"); // bucket CORS ต้อง ExposeHeaders: ETag
      if (res.ok && etag) return etag;
      if (res.status === 403) break; // URL หมดอายุ → ขอ URL ใหม่จาก API
    } catch {
      // network error → retry part เดิม
    }
    await new Promise((r) => setTimeout(r, 2 ** attempt * 500 + Math.random() * 250));
  }
  throw new Error("upload part failed: resume ด้วย GET /videos/:id/upload");
}

async function postJson<T = unknown>(url: string, body: unknown, key?: string): Promise<T> {
  const res = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(key ? { "Idempotency-Key": key } : {}),
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`${url} → ${res.status}`);
  return (await res.json()) as T;
}

Data model: job หนึ่งแถวต่อ rendition

transcode_jobs เป็น source of truth ของงาน ไม่ใช่คิว คิวเป็นแค่ "กริ่ง" ที่ปลุก worker คอลัมน์ที่สำคัญที่สุดคือ attempt (fencing token) และ lease_until ส่วน UNIQUE (video_id, rendition) ทำให้ fan-out ซ้ำกี่ครั้งก็ได้ job ชุดเดิม

CODEer.mmd
erDiagram
    VIDEO ||--o{ TRANSCODE_JOB : "fan-out"
    VIDEO ||--o{ OUTBOX : emits

    VIDEO {
        uuid id PK
        uuid owner_id
        text status "UPLOADING|UPLOADED|PROCESSING|READY|FAILED"
        text source_key
        text s3_upload_id
        bigint size_bytes
        bigint duration_ms
        int renditions_total
        int renditions_done
    }
    TRANSCODE_JOB {
        uuid id PK
        uuid video_id FK
        text rendition "UNIQUE(video_id, rendition)"
        text status "QUEUED|RUNNING|DONE|FAILED"
        int attempt "fencing token"
        text worker_id
        timestamptz lease_until
        text output_prefix "ผลของ attempt ที่ชนะ"
    }
    OUTBOX {
        bigint id PK
        uuid aggregate_id
        text event_type
        jsonb payload
    }
RESULT

กำลังวาด diagram…

schema.sql
CREATE TABLE videos (
  id               uuid PRIMARY KEY,
  owner_id         uuid        NOT NULL,
  status           text        NOT NULL DEFAULT 'UPLOADING'
                   CHECK (status IN ('UPLOADING','UPLOADED','PROCESSING','READY','FAILED')),
  source_key       text        NOT NULL,              -- raw/{id}/source
  s3_upload_id     text,                               -- multipart upload id
  size_bytes       bigint      CHECK (size_bytes <= 2147483648),
  duration_ms      bigint,                             -- จาก ffprobe ใช้คำนวณ %
  renditions_total int         NOT NULL DEFAULT 0,
  renditions_done  int         NOT NULL DEFAULT 0,
  created_at       timestamptz NOT NULL DEFAULT now(),
  updated_at       timestamptz NOT NULL DEFAULT now(),
  CHECK (renditions_done <= renditions_total)
);

CREATE TABLE transcode_jobs (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  video_id      uuid NOT NULL REFERENCES videos (id),
  rendition     text NOT NULL CHECK (rendition IN ('1080p','720p','480p','360p')),
  status        text NOT NULL DEFAULT 'QUEUED'
                CHECK (status IN ('QUEUED','RUNNING','DONE','FAILED')),
  attempt       int  NOT NULL DEFAULT 0,     -- fencing token: +1 ทุกครั้งที่ claim
  worker_id     text,
  lease_until   timestamptz,                 -- เลยเวลานี้ = worker ถือว่าตายแล้ว
  output_prefix text,                        -- ชี้ไปที่ renditions/{video}/{rendition}/a{attempt}/
  last_error    text,
  started_at    timestamptz,
  finished_at   timestamptz,
  updated_at    timestamptz NOT NULL DEFAULT now(),
  UNIQUE (video_id, rendition),              -- fan-out ซ้ำก็ไม่เกิด job ซ้ำ
  CHECK (status <> 'DONE' OR output_prefix IS NOT NULL)
);
CREATE INDEX transcode_jobs_running_lease
  ON transcode_jobs (lease_until) WHERE status = 'RUNNING';

CREATE TABLE outbox (
  id           bigserial PRIMARY KEY,
  aggregate_id uuid        NOT NULL,
  event_type   text        NOT NULL,       -- VideoUploaded | TranscodeRequested | PublishRequested | ...
  payload      jsonb       NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  published_at timestamptz
);
fanout.sql
-- Probe worker: หลัง ffprobe ผ่าน → fan-out แบบ idempotent ใน statement เดียว
-- $3 = rendition ที่ไม่ upscale เช่น source 720p → {720p,480p,360p}
WITH v AS (
  UPDATE videos
  SET status = 'PROCESSING', duration_ms = $2,
      renditions_total = cardinality($3::text[]), updated_at = now()
  WHERE id = $1 AND status = 'UPLOADED'          -- message probe ซ้ำ → 0 row → ไม่ทำอะไร
  RETURNING id
), jobs AS (
  INSERT INTO transcode_jobs (video_id, rendition)
  SELECT v.id, r FROM v, unnest($3::text[]) AS r
  ON CONFLICT (video_id, rendition) DO NOTHING
  RETURNING id
)
INSERT INTO outbox (aggregate_id, event_type, payload)
SELECT $1, 'TranscodeRequested', jsonb_build_object('jobId', jobs.id)
FROM jobs;                                         -- relay ส่งเข้า SQS transcode-jobs

Lifecycle ของ job และ video

ทุกลูกศรต้องทำด้วย SQL ที่เช็ค state ปัจจุบัน (และ attempt) ใน WHERE ลูกศรที่คนมักลืมคือ RUNNING → QUEUED (release ตอน transient error หรือ SIGTERM) และ QUEUED → FAILED จาก DLQ handler และ video ต้องเป็น READY หลังจากมี master playlist แล้วเท่านั้น

CODEjob-lifecycle.mmd
stateDiagram-v2
    [*] --> QUEUED: probe fan-out
    QUEUED --> RUNNING: claim (attempt+1, lease 3m)
    RUNNING --> RUNNING: heartbeat ต่อ lease ทุก 1m
    RUNNING --> DONE: commit WHERE attempt = n
    RUNNING --> QUEUED: transient error / SIGTERM → release
    RUNNING --> FAILED: permanent error / ครบ maxReceiveCount
    QUEUED --> FAILED: DLQ handler
    FAILED --> QUEUED: admin redrive หลังแก้ bug
    DONE --> [*]

    note right of RUNNING
        worker ตาย = heartbeat หยุด
        lease หมด → worker อื่น claim ได้
        ด้วย attempt ใหม่ (fencing)
    end note
RESULT

กำลังวาด diagram…

CODEvideo-lifecycle.mmd
stateDiagram-v2
    [*] --> UPLOADING: POST /videos
    UPLOADING --> UPLOADED: complete + HeadObject ≤ 2GB
    UPLOADING --> FAILED: ค้างเกิน 24 ชม. → abort multipart
    UPLOADED --> PROCESSING: ffprobe ผ่าน → fan-out
    UPLOADED --> FAILED: ไม่ใช่ไฟล์วิดีโอ
    PROCESSING --> READY: ครบทุก rendition + master.m3u8
    PROCESSING --> FAILED: job ใด FAILED ถาวร
    READY --> [*]
RESULT

กำลังวาด diagram…

Idempotent output: ทำซ้ำได้ แต่ commit ได้ครั้งเดียว

ระบบที่ส่งงานแบบ at-least-once ต้องยอมรับว่า งานเดียวอาจถูกทำพร้อมกัน 2 ที่ (heartbeat พลาด, network partition, SQS ส่งซ้ำ) เราจึงไม่พยายามทำให้ "ทำครั้งเดียว" แต่ทำให้ ผลลัพธ์ถูก commit ครั้งเดียว ผลของแต่ละ attempt อยู่คนละ prefix แล้ว DB เลือกว่า prefix ไหนเป็นผลจริง ในขั้นตอนเดียวกับการเปลี่ยน state

output-keys.txt
ผลลัพธ์ของ job ผูกกับ (video, rendition, attempt) ไม่ใช่ "ใครเขียนทีหลังชนะ"

s3://media/renditions/v9/720p/a1/index.m3u8   ← worker A (zombie) เขียนทีหลังก็ไม่ทับใคร
s3://media/renditions/v9/720p/a2/index.m3u8   ← worker B commit ได้ → output_prefix ชี้ที่นี่
s3://media/renditions/v9/master.m3u8          ← publisher สร้างจาก output_prefix ของทุก job

commit:  UPDATE transcode_jobs SET status='DONE', output_prefix='.../a2/'
         WHERE id = $job AND attempt = 2 AND status = 'RUNNING'   → 1 row
zombie:  ... WHERE attempt = 1 ...                                → 0 row → ทิ้งผล
GC:      ลบ prefix a{k} ที่ไม่ใช่ output_prefix ทุกวัน
CODEzombie.mmd
sequenceDiagram
    participant A as Worker A attempt 1
    participant B as Worker B attempt 2
    participant DB as PostgreSQL
    participant S3 as S3

    Note over A: network partition 6 นาที ต่อ lease ไม่ได้
    B->>DB: claim เพราะ lease ของ A หมด → attempt 2
    B->>S3: PUT .../720p/a2/
    B->>DB: UPDATE DONE WHERE attempt = 2 → 1 row
    Note over A: กลับมา ffmpeg จบพอดี
    A->>S3: PUT .../720p/a1/ ไม่ทับ a2
    A->>DB: UPDATE DONE WHERE attempt = 1 → 0 row
    Note over A: lost lease → ทิ้งผล a1 ให้ GC ลบ
RESULT

กำลังวาด diagram…

commit.go
// commit: ปิดงานแบบมี fencing + fan-in ใน transaction เดียว
func (w *Worker) commit(ctx context.Context, c Claim, prefix string) error {
	return pgx.BeginFunc(ctx, w.db, func(tx pgx.Tx) error {
		tag, err := tx.Exec(ctx, `
			UPDATE transcode_jobs
			SET status = 'DONE', output_prefix = $3, lease_until = NULL,
			    finished_at = now(), updated_at = now()
			WHERE id = $1 AND attempt = $2 AND status = 'RUNNING'`,
			c.JobID, c.Attempt, prefix)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return errLostLease // มี attempt ใหม่กว่าแล้ว → ผลของเราไม่ถูกใช้
		}

		// Fan-in: UPDATE ถือ row lock ของ video → commit ที่มาพร้อมกันถูกเรียงคิว
		// ตัวที่เห็น done == total มีได้ตัวเดียว (ไม่ใช้ SELECT count(*) ที่ race ได้)
		var done, total int
		if err := tx.QueryRow(ctx, `
			UPDATE videos SET renditions_done = renditions_done + 1, updated_at = now()
			WHERE id = $1
			RETURNING renditions_done, renditions_total`, c.VideoID).Scan(&done, &total); err != nil {
			return err
		}
		if done < total {
			return nil
		}
		return enqueue(ctx, tx, c.VideoID, "PublishRequested", map[string]any{"videoId": c.VideoID})
	})
}

// fail: บันทึก FAILED ถาวร (ไฟล์เสีย / ครบจำนวน retry) แล้วแจ้ง video
func (w *Worker) fail(ctx context.Context, c Claim, cause error) error {
	return pgx.BeginFunc(ctx, w.db, func(tx pgx.Tx) error {
		tag, err := tx.Exec(ctx, `
			UPDATE transcode_jobs
			SET status = 'FAILED', last_error = $3, lease_until = NULL, finished_at = now()
			WHERE id = $1 AND attempt = $2 AND status = 'RUNNING'`,
			c.JobID, c.Attempt, cause.Error())
		if err != nil || tag.RowsAffected() == 0 {
			return err
		}
		tag, err = tx.Exec(ctx, `
			UPDATE videos SET status = 'FAILED', updated_at = now()
			WHERE id = $1 AND status = 'PROCESSING'`, c.VideoID)
		if err != nil || tag.RowsAffected() == 0 {
			return err
		}
		return enqueue(ctx, tx, c.VideoID, "VideoFailed", map[string]any{
			"rendition": c.Rendition, "error": cause.Error(),
		})
	})
}

func enqueue(ctx context.Context, tx pgx.Tx, id uuid.UUID, eventType string, payload any) error {
	_, err := tx.Exec(ctx, `
		INSERT INTO outbox (aggregate_id, event_type, payload) VALUES ($1, $2, $3)`,
		id, eventType, payload)
	return err
}
publisher.go
// Publisher: consumer ของ PublishRequested (at-least-once → ต้อง idempotent)
func (p *Publisher) Publish(ctx context.Context, videoID uuid.UUID) error {
	rows, err := p.db.Query(ctx, `
		SELECT rendition, output_prefix FROM transcode_jobs
		WHERE video_id = $1 AND status = 'DONE'
		ORDER BY rendition`, videoID)
	if err != nil {
		return err
	}
	outputs, err := pgx.CollectRows(rows, pgx.RowToStructByPos[RenditionOutput])
	if err != nil {
		return err
	}

	// เนื้อหา master playlist ขึ้นกับข้อมูลใน DB อย่างเดียว → PUT ซ้ำได้ผลเหมือนเดิม
	master := buildMasterPlaylist(videoID, outputs)
	if _, err := p.s3.PutObject(ctx, &s3.PutObjectInput{
		Bucket:      aws.String(p.bucket),
		Key:         aws.String(fmt.Sprintf("renditions/%s/master.m3u8", videoID)),
		Body:        strings.NewReader(master),
		ContentType: aws.String("application/vnd.apple.mpegurl"),
	}); err != nil {
		return err
	}

	// READY หลัง master.m3u8 มีอยู่จริงแล้วเท่านั้น → ผู้ใช้กดเล่นแล้วไม่เจอ 404
	return pgx.BeginFunc(ctx, p.db, func(tx pgx.Tx) error {
		tag, err := tx.Exec(ctx, `
			UPDATE videos SET status = 'READY', updated_at = now()
			WHERE id = $1 AND status = 'PROCESSING'`, videoID)
		if err != nil || tag.RowsAffected() == 0 {
			return err // 0 row = publish ไปแล้ว (message ซ้ำ)
		}
		return enqueue(ctx, tx, videoID, "VideoReady", map[string]any{"videoId": videoID})
	})
}

Progress: ffmpeg → Redis pub/sub → SSE

ffmpeg มี -progress pipe:1 ที่พิมพ์ out_time_us ออกมาเรื่อยๆ หารด้วย duration จาก ffprobe ก็ได้เปอร์เซ็นต์ worker throttle ให้ส่งทุก 2 วินาที เขียน HSET (snapshot) และ PUBLISH (push) ลง Redis ส่วน API เปิด SSE ให้ browser Progress ถือเป็น best effort: Redis ล่มแล้ว job ต้องเดินต่อ สถานะจริงยังอยู่ใน DB

progress.go
// Progress ไม่ใช่ source of truth: หายได้ ช้าได้ แต่ห้ามทำให้ job พัง
type Progress struct {
	rdb  *redis.Client
	mu   sync.Mutex
	last time.Time
}

func progressKey(videoID uuid.UUID) string { return "video:" + videoID.String() + ":progress" }

func (p *Progress) Report(ctx context.Context, c Claim, pct float64) {
	p.mu.Lock()
	if pct < 100 && time.Since(p.last) < 2*time.Second { // throttle: ffmpeg รายงานหลายครั้ง/วินาที
		p.mu.Unlock()
		return
	}
	p.last = time.Now()
	p.mu.Unlock()

	key := progressKey(c.VideoID)
	msg, _ := json.Marshal(map[string]any{"rendition": c.Rendition, "pct": math.Round(pct*10) / 10})

	pipe := p.rdb.TxPipeline()
	pipe.HSet(ctx, key, c.Rendition, fmt.Sprintf("%.1f", pct)) // snapshot ให้คนที่เพิ่งเปิดหน้า
	pipe.Expire(ctx, key, 24*time.Hour)
	pipe.Publish(ctx, key, msg) // push ให้ SSE ที่เปิดอยู่
	if _, err := pipe.Exec(ctx); err != nil {
		slog.Warn("progress publish failed", "video", c.VideoID, "err", err) // log แล้วไปต่อ
	}
}

// SSE endpoint: GET /videos/{id}/events
func (h *Handler) VideoEvents(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	videoID, err := uuid.Parse(r.PathValue("id"))
	if err != nil {
		http.Error(w, "bad id", http.StatusBadRequest)
		return
	}
	status, err := h.videos.StatusForOwner(ctx, videoID, userID(ctx)) // สถานะจริงจาก DB
	if err != nil {
		http.Error(w, "not found", http.StatusNotFound)
		return
	}
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("X-Accel-Buffering", "no") // ปิด buffering ของ nginx

	// subscribe ให้สำเร็จ "ก่อน" อ่าน snapshot → ไม่มีช่องว่างที่ event หลุด
	sub := h.rdb.Subscribe(ctx, progressKey(videoID))
	defer sub.Close()
	if _, err := sub.Receive(ctx); err != nil {
		slog.Warn("redis subscribe failed, client จะ fallback ไป poll", "err", err)
	}
	pct, _ := h.rdb.HGetAll(ctx, progressKey(videoID)).Result()
	writeEvent(w, "snapshot", map[string]any{"status": status, "renditions": pct})
	flusher.Flush()
	if status == "READY" || status == "FAILED" {
		return
	}

	msgs := sub.Channel()
	ping := time.NewTicker(15 * time.Second)
	defer ping.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case m, ok := <-msgs:
			if !ok {
				return
			}
			// payload มีทั้ง {rendition,pct} จาก worker และ {status} จาก consumer ของ VideoReady/VideoFailed
			fmt.Fprintf(w, "event: progress\ndata: %s\n\n", m.Payload)
			flusher.Flush()
		case <-ping.C:
			fmt.Fprint(w, ": ping\n\n") // กัน load balancer ตัด connection ที่เงียบ
			flusher.Flush()
		}
	}
}
progress-client.ts
type ProgressState = {
  status: "PROCESSING" | "READY" | "FAILED" | string;
  renditions: Record<string, number>;
};

export function watchProgress(videoId: string, render: (s: ProgressState & { overall: number }) => void) {
  const state: ProgressState = { status: "PROCESSING", renditions: {} };
  const es = new EventSource(`/videos/${videoId}/events`, { withCredentials: true });

  const emit = () => {
    const values = Object.values(state.renditions);
    const overall = values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;
    render({ ...state, overall });
    if (state.status === "READY" || state.status === "FAILED") es.close();
  };

  // server ส่ง snapshot ทุกครั้งที่ต่อใหม่ → EventSource reconnect เองโดยไม่พลาดสถานะ
  es.addEventListener("snapshot", (e) => {
    const snap = JSON.parse((e as MessageEvent<string>).data) as {
      status: string;
      renditions: Record<string, string>;
    };
    state.status = snap.status;
    for (const [r, pct] of Object.entries(snap.renditions)) state.renditions[r] = Number(pct);
    emit();
  });

  es.addEventListener("progress", (e) => {
    const ev = JSON.parse((e as MessageEvent<string>).data) as {
      rendition?: string;
      pct?: number;
      status?: string;
    };
    if (ev.rendition && ev.pct !== undefined) {
      // ไม่ให้ % ถอยหลัง ยกเว้นงานถูก retry (UI แสดง "กำลังลองใหม่")
      state.renditions[ev.rendition] = Math.max(state.renditions[ev.rendition] ?? 0, ev.pct);
    }
    if (ev.status) state.status = ev.status;
    emit();
  });

  return () => es.close();
}

04แนวทาง A: Work Queue + Stateless Workers

★ แนวทางที่แนะนำให้เสนอในห้องสอบ

อัปโหลดตรงเข้า object storage ด้วย presigned URL แล้วส่ง job เข้า SQS ต่อความละเอียด worker ต่อเวลา visibility timeout ระหว่างทำ และ scale ตามความยาวคิว

เหมาะเมื่อ

Pipeline ขั้นตอนไม่มาก (probe → transcode ×4 → publish) ทีมอยากใช้ managed queue ที่ดูแลง่าย และเป็นคำตอบหลักในห้องสอบ

ไม่เหมาะเมื่อ

Pipeline มีหลายขั้นที่ขึ้นต่อกัน มีการรอคน (review) หรือต้องการ SLA และ retry policy ต่อขั้นที่ซับซ้อน เพราะจะต้องเขียน state machine เองทั้งหมด

Architecture

แยก 3 ช่วง: ingest (presigned upload), processing (probe → fan-out เป็น job ต่อ rendition เข้า SQS, worker 1 pod ต่อ 1 งาน) และ delivery (publisher เขียน master.m3u8 แล้วเสิร์ฟผ่าน CDN) job ทุกตัวถูกสร้างผ่าน outbox จึงไม่มี dual write ระหว่าง DB กับ SQS

CODEarchitecture-a.mmd
flowchart LR
    U[Client<br/>Web / Mobile] -->|1 create upload| API[Video API<br/>stateless]
    U -->|2 PUT parts ตรง| S3R[(S3 raw bucket)]
    U -->|3 complete| API
    U -. SSE progress .-> API
    API --> PG[(PostgreSQL<br/>videos · jobs · outbox)]
    PG -.outbox.-> RELAY[Outbox Relay]
    RELAY --> QP[[SQS probe-jobs]]
    QP --> PW[Probe Worker<br/>ffprobe + fan-out]
    PW --> PG
    RELAY --> QT[[SQS transcode-jobs]]
    QT --> TW[Transcode Workers<br/>1 job ต่อ pod · spot]
    QT -. maxReceiveCount .-> DLQ[[transcode-dlq]]
    DLQ --> DH[DLQ Handler<br/>FAILED + alert]
    DH --> PG
    TW --> S3R
    TW --> S3O[(S3 renditions<br/>HLS)]
    TW --> PG
    TW --> RD[(Redis<br/>progress pub/sub)]
    API --> RD
    RELAY --> PUB[Publisher<br/>master.m3u8]
    PUB --> S3O
    S3O --> CDN[CDN] --> U
    AS[Autoscaler<br/>backlog per worker] -. scale .-> TW
RESULT

กำลังวาด diagram…

CODEhappy-path-a.mmd
sequenceDiagram
    autonumber
    actor U as User
    participant API as Video API
    participant S3 as S3
    participant DB as PostgreSQL
    participant Q as SQS
    participant W as Transcode Worker
    participant R as Redis

    U->>API: POST /videos size 1.4GB
    API->>S3: CreateMultipartUpload
    API->>DB: INSERT video UPLOADING
    API-->>U: videoId + 22 presigned part URLs
    U->>S3: PUT part 1..22 ขนาน 4 ตัว
    U->>API: POST /videos/v9/complete ETags
    API->>S3: CompleteMultipartUpload + HeadObject
    API->>DB: video UPLOADED + outbox VideoUploaded
    Note over DB,Q: relay → probe worker → ffprobe → fan-out 4 jobs + outbox
    Q->>W: job 720p
    W->>DB: claim → RUNNING attempt 1
    loop ทุก 2 วินาที
        W->>R: HSET + PUBLISH 720p 42%
        R-->>U: SSE progress
    end
    W->>S3: PUT renditions/v9/720p/a1/
    W->>DB: DONE WHERE attempt 1 + renditions_done 4 of 4
    W->>Q: DeleteMessage
    Note over DB,S3: publisher เขียน master.m3u8 → video READY
    R-->>U: SSE status READY
RESULT

กำลังวาด diagram…

ทำไม ack ก่อน หรือ timeout ตายตัวถึงพัง

naive.go
// ❌ ack ก่อนทำ (at-most-once): worker ตายระหว่าง ffmpeg → งานหายเงียบ
out, _ := sqsClient.ReceiveMessage(ctx, in)
for _, m := range out.Messages {
	sqsClient.DeleteMessage(ctx, &sqs.DeleteMessageInput{QueueUrl: q, ReceiptHandle: m.ReceiptHandle})
	transcode(m) // 5–30 นาที ถ้า OOM ตรงนี้ ไม่มีใครรู้ และ job ค้าง RUNNING ตลอดไป
}

// ❌ แก้โดยตั้ง visibility timeout = 45 นาทีตายตัว ไม่มี heartbeat:
//    worker ตายนาทีที่ 1 → ต้องรออีก 44 นาทีกว่างานจะกลับเข้าคิว
// ❌ ตั้ง visibility timeout = 5 นาที ไม่มี heartbeat:
//    งาน 20 นาทีโผล่กลับเข้าคิวระหว่างทำ → worker อื่นทำซ้ำพร้อมกัน

Worker loop: claim → heartbeat → commit → ack

ลำดับที่ต้องจำ: claim ใน DB (ได้ attempt ใหม่) → ทำงานโดยมี heartbeat ที่ต่อทั้ง DB lease และ SQS visibility → commit แบบมี fencing → DeleteMessage หลัง commit เท่านั้น ถ้าตายตรงไหนก็ตาม message ยังอยู่ในคิวและจะกลับมาเอง

worker.go
package worker

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"strconv"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgxpool"
)

const (
	leaseTTL        = 3 * time.Minute // visibility timeout และ DB lease ที่ต่อแต่ละครั้ง
	heartbeatEvery  = 1 * time.Minute // ต่อก่อนหมด → พลาด heartbeat ได้ 1–2 ครั้ง
	stallAfter      = 5 * time.Minute // ffmpeg ไม่ขยับเกินนี้ = ค้าง
	maxReceiveCount = 4               // ต้องตรงกับ redrive policy ของคิว
)

var (
	errTerminal      = errors.New("job already terminal")
	errLeasedByOther = errors.New("job leased by another worker")
	errLostLease     = errors.New("lost lease: fenced by newer attempt")
	errStalled       = errors.New("ffmpeg made no progress")
)

type JobMessage struct {
	JobID uuid.UUID `json:"jobId"`
}

type Claim struct {
	JobID      uuid.UUID
	VideoID    uuid.UUID
	Rendition  string
	Attempt    int32 // fencing token
	SourceKey  string
	DurationMs int64
}

type Worker struct {
	id       string // hostname/pod name
	db       *pgxpool.Pool
	sqs      *sqs.Client
	queueURL string
	tc       *Transcoder
	progress *Progress
}

func (w *Worker) Run(ctx context.Context) error {
	for ctx.Err() == nil {
		out, err := w.sqs.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
			QueueUrl:            aws.String(w.queueURL),
			MaxNumberOfMessages: 1,  // 1 pod 1 งาน: ffmpeg ใช้ CPU เต็มอยู่แล้ว
			WaitTimeSeconds:     20, // long polling
			VisibilityTimeout:   int32(leaseTTL.Seconds()),
			MessageSystemAttributeNames: []types.MessageSystemAttributeName{
				types.MessageSystemAttributeNameApproximateReceiveCount,
			},
		})
		if err != nil {
			slog.Warn("receive failed", "err", err)
			select { // SQS มีปัญหา → พักก่อน ไม่วน loop เปล่า
			case <-ctx.Done():
			case <-time.After(2 * time.Second):
			}
			continue
		}
		for _, m := range out.Messages {
			w.handle(ctx, m)
		}
	}
	return nil
}

func (w *Worker) handle(ctx context.Context, m types.Message) {
	var msg JobMessage
	if err := json.Unmarshal([]byte(aws.ToString(m.Body)), &msg); err != nil {
		slog.Error("malformed message: ไม่ ack ปล่อยให้ไป DLQ", "err", err)
		return
	}
	receives, _ := strconv.Atoi(m.Attributes[string(types.MessageSystemAttributeNameApproximateReceiveCount)])

	claim, err := w.claim(ctx, msg.JobID)
	switch {
	case errors.Is(err, errTerminal):
		w.ack(ctx, m) // message ซ้ำ หรือ crash หลัง commit ก่อน ack → แค่ลบ
		return
	case errors.Is(err, errLeasedByOther):
		w.visibleAfter(ctx, m, leaseTTL) // อีกตัวยังทำอยู่ → กลับมาดูใหม่ภายหลัง
		return
	case err != nil:
		return // DB ล่ม → ไม่ ack, SQS ส่งกลับมาเองเมื่อ visibility หมด
	}

	jobCtx, cancel := context.WithCancelCause(ctx)
	hb := w.startHeartbeat(jobCtx, cancel, m.ReceiptHandle, claim)
	prefix, runErr := w.tc.Run(jobCtx, claim, func(pct float64) {
		hb.touch()
		w.progress.Report(jobCtx, claim, pct)
	})
	cancel(nil) // หยุด heartbeat ก่อน commit → ไม่แข่งกัน
	hb.wait()

	switch {
	case errors.Is(context.Cause(jobCtx), errLostLease):
		return // มี attempt ใหม่กว่าแล้ว ผลของเราอยู่ใต้ prefix a{n} ที่ไม่มีใครอ้างถึง
	case ctx.Err() != nil:
		// SIGTERM (scale-in / spot interruption) → คืนงานทันที ไม่ต้องรอ lease หมด
		w.release(context.WithoutCancel(ctx), m, claim, "shutdown", 0)
		return
	case runErr != nil && isPermanent(runErr):
		if w.fail(ctx, claim, runErr) == nil {
			w.ack(ctx, m) // ไฟล์เสีย retry ไปก็เสียเหมือนเดิม
		}
		return
	case runErr != nil && receives >= maxReceiveCount:
		if w.fail(ctx, claim, runErr) == nil {
			w.ack(ctx, m) // ครั้งสุดท้ายแล้ว บันทึก FAILED เองก่อนหลุดไป DLQ
		}
		return
	case runErr != nil:
		w.release(ctx, m, claim, runErr.Error(), backoff(receives)) // transient
		return
	}

	if err := w.commit(ctx, claim, prefix); err != nil {
		// errLostLease → zombie ทิ้งผล / error อื่น → ไม่ ack, redeliver แล้วทำใหม่ได้ (output ผูกกับ attempt)
		slog.Warn("commit failed", "job", claim.JobID, "err", err)
		return
	}
	w.ack(ctx, m) // ack หลัง commit เท่านั้น
}

func backoff(receives int) time.Duration {
	return min(30*time.Second<<max(receives-1, 0), 10*time.Minute)
}
claim-heartbeat.go
// claim: atomic ใน statement เดียว ได้ attempt ใหม่เป็น fencing token
func (w *Worker) claim(ctx context.Context, jobID uuid.UUID) (Claim, error) {
	c := Claim{JobID: jobID}
	err := w.db.QueryRow(ctx, `
		UPDATE transcode_jobs j
		SET status = 'RUNNING', attempt = j.attempt + 1, worker_id = $2,
		    lease_until = now() + make_interval(secs => $3),
		    started_at = now(), updated_at = now()
		FROM videos v
		WHERE j.id = $1 AND v.id = j.video_id
		  AND (j.status = 'QUEUED' OR (j.status = 'RUNNING' AND j.lease_until < now()))
		RETURNING j.video_id, j.rendition, j.attempt, v.source_key, v.duration_ms`,
		jobID, w.id, leaseTTL.Seconds(),
	).Scan(&c.VideoID, &c.Rendition, &c.Attempt, &c.SourceKey, &c.DurationMs)
	if !errors.Is(err, pgx.ErrNoRows) {
		return c, err
	}

	var status string
	err = w.db.QueryRow(ctx, `SELECT status FROM transcode_jobs WHERE id = $1`, jobID).Scan(&status)
	switch {
	case errors.Is(err, pgx.ErrNoRows):
		return c, errTerminal // video ถูกลบไปแล้ว
	case err != nil:
		return c, err
	case status == "DONE" || status == "FAILED":
		return c, errTerminal
	default:
		return c, errLeasedByOther // RUNNING และ lease ยังไม่หมด
	}
}

type heartbeat struct {
	lastProgress atomic.Int64 // unix nano
	done         chan struct{}
}

func (h *heartbeat) touch() { h.lastProgress.Store(time.Now().UnixNano()) }
func (h *heartbeat) wait()  { <-h.done }

// heartbeat ต่อทั้ง DB lease และ SQS visibility และผูกกับ "progress จริง"
// ถ้า ffmpeg ค้างแต่ process ยังอยู่ timer ธรรมดาจะต่อ lease ไปเรื่อยๆ → งานค้างตลอดกาล
func (w *Worker) startHeartbeat(ctx context.Context, cancel context.CancelCauseFunc, receipt *string, c Claim) *heartbeat {
	h := &heartbeat{done: make(chan struct{})}
	h.touch()
	go func() {
		defer close(h.done)
		t := time.NewTicker(heartbeatEvery)
		defer t.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-t.C:
			}
			if time.Since(time.Unix(0, h.lastProgress.Load())) > stallAfter {
				cancel(errStalled) // kill ffmpeg → handle() release แล้ว retry ที่เครื่องอื่น
				return
			}
			tag, err := w.db.Exec(ctx, `
				UPDATE transcode_jobs
				SET lease_until = now() + make_interval(secs => $3), updated_at = now()
				WHERE id = $1 AND attempt = $2 AND status = 'RUNNING'`,
				c.JobID, c.Attempt, leaseTTL.Seconds())
			if err == nil && tag.RowsAffected() == 0 {
				cancel(errLostLease) // มีคน claim attempt ใหม่ไปแล้ว → หยุดทันที
				return
			}
			if _, err := w.sqs.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
				QueueUrl:          aws.String(w.queueURL),
				ReceiptHandle:     receipt,
				VisibilityTimeout: int32(leaseTTL.Seconds()),
			}); err != nil {
				// พลาดครั้งเดียวยังไม่เป็นไร ถ้า message ถูกส่งให้คนอื่น DB fencing จะตัดสินเอง
				slog.Warn("extend visibility failed", "job", c.JobID, "err", err)
			}
		}
	}()
	return h
}

func (w *Worker) ack(ctx context.Context, m types.Message) {
	if _, err := w.sqs.DeleteMessage(ctx, &sqs.DeleteMessageInput{
		QueueUrl: aws.String(w.queueURL), ReceiptHandle: m.ReceiptHandle,
	}); err != nil {
		slog.Warn("delete failed: message จะกลับมาแล้ว claim เจอ DONE", "err", err)
	}
}

func (w *Worker) visibleAfter(ctx context.Context, m types.Message, d time.Duration) {
	_, _ = w.sqs.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
		QueueUrl: aws.String(w.queueURL), ReceiptHandle: m.ReceiptHandle,
		VisibilityTimeout: int32(d.Seconds()), // 0 = ให้คนอื่นหยิบได้ทันที
	})
}

// release: คืนงานเข้าคิว (transient error / shutdown)
func (w *Worker) release(ctx context.Context, m types.Message, c Claim, reason string, after time.Duration) {
	_, _ = w.db.Exec(ctx, `
		UPDATE transcode_jobs SET status = 'QUEUED', lease_until = NULL, last_error = $3, updated_at = now()
		WHERE id = $1 AND attempt = $2 AND status = 'RUNNING'`, c.JobID, c.Attempt, reason)
	w.visibleAfter(ctx, m, after)
}
ffmpeg.go
var ErrInvalidInput = errors.New("invalid input") // permanent: retry ไม่ช่วย

func isPermanent(err error) bool { return errors.Is(err, ErrInvalidInput) }

type Rung struct{ Height, Kbps int }

var ladder = map[string]Rung{
	"1080p": {1080, 5000}, "720p": {720, 2800}, "480p": {480, 1400}, "360p": {360, 800},
}

// Run: download → ffmpeg → upload ไปที่ prefix ของ attempt นี้เท่านั้น
func (t *Transcoder) Run(ctx context.Context, c Claim, onProgress func(pct float64)) (string, error) {
	dir := filepath.Join(t.scratch, c.JobID.String(), fmt.Sprintf("a%d", c.Attempt))
	defer os.RemoveAll(filepath.Join(t.scratch, c.JobID.String()))
	if err := os.MkdirAll(filepath.Join(dir, "out"), 0o755); err != nil {
		return "", err
	}
	src := filepath.Join(dir, "source")
	if err := t.download(ctx, c.SourceKey, src); err != nil { // GetObject → local NVMe
		return "", err
	}
	if err := runFFmpeg(ctx, src, filepath.Join(dir, "out"), ladder[c.Rendition], c.DurationMs*1000, onProgress); err != nil {
		return "", err
	}
	prefix := fmt.Sprintf("renditions/%s/%s/a%d/", c.VideoID, c.Rendition, c.Attempt)
	return prefix, t.uploadDir(ctx, filepath.Join(dir, "out"), prefix)
}

func runFFmpeg(ctx context.Context, in, outDir string, r Rung, durationUs int64, onProgress func(float64)) error {
	args := []string{
		"-hide_banner", "-nostdin", "-y", "-loglevel", "error",
		"-i", in,
		"-vf", fmt.Sprintf("scale=-2:%d", r.Height),
		"-c:v", "libx264", "-preset", "veryfast", "-profile:v", "high",
		"-b:v", fmt.Sprintf("%dk", r.Kbps),
		"-maxrate", fmt.Sprintf("%dk", r.Kbps*107/100),
		"-bufsize", fmt.Sprintf("%dk", r.Kbps*2),
		// keyframe ทุก 2 วินาทีเท่ากันทุก rendition → player สลับความละเอียดได้ที่รอยต่อ segment
		"-force_key_frames", "expr:gte(t,n_forced*2)", "-sc_threshold", "0",
		"-c:a", "aac", "-b:a", "128k", "-ac", "2",
		"-f", "hls", "-hls_time", "4", "-hls_playlist_type", "vod",
		"-hls_segment_filename", filepath.Join(outDir, "seg_%05d.ts"),
		"-progress", "pipe:1", "-nostats", // key=value ทาง stdout
		filepath.Join(outDir, "index.m3u8"),
	}
	cmd := exec.CommandContext(ctx, "ffmpeg", args...) // ctx ถูก cancel → SIGKILL ffmpeg
	cmd.WaitDelay = 10 * time.Second
	stderr := &tailBuffer{max: 4096}
	cmd.Stderr = stderr
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	if err := cmd.Start(); err != nil {
		return err
	}

	sc := bufio.NewScanner(stdout)
	for sc.Scan() {
		k, v, ok := strings.Cut(sc.Text(), "=")
		if !ok || k != "out_time_us" || durationUs <= 0 {
			continue
		}
		if us, err := strconv.ParseInt(v, 10, 64); err == nil { // ค่าแรกอาจเป็น N/A
			onProgress(min(float64(us)/float64(durationUs)*100, 99.9))
		}
	}

	if err := cmd.Wait(); err != nil { // Wait หลังอ่าน stdout จนหมดเท่านั้น
		if ctx.Err() != nil {
			return context.Cause(ctx)
		}
		msg := stderr.String()
		if strings.Contains(msg, "Invalid data found when processing input") ||
			strings.Contains(msg, "moov atom not found") {
			return fmt.Errorf("%w: %s", ErrInvalidInput, msg)
		}
		return fmt.Errorf("ffmpeg: %w: %s", err, msg) // transient เช่น OOM, disk เต็ม
	}
	onProgress(100)
	return nil
}

// tailBuffer เก็บ stderr แค่ท้ายสุด ไม่ให้ log ยาวกิน memory
type tailBuffer struct {
	buf []byte
	max int
}

func (t *tailBuffer) Write(p []byte) (int, error) {
	t.buf = append(t.buf, p...)
	if len(t.buf) > t.max {
		t.buf = t.buf[len(t.buf)-t.max:]
	}
	return len(p), nil
}

func (t *tailBuffer) String() string { return string(t.buf) }

Worker ตายกลางทาง

CODEworker-dies.mmd
sequenceDiagram
    autonumber
    participant Q as SQS transcode-jobs
    participant A as Worker A
    participant B as Worker B
    participant DB as PostgreSQL
    participant S3 as S3

    Q->>A: receive job 720p, visibility 3m
    A->>DB: claim → RUNNING attempt 1, lease 3m
    loop ทุก 1 นาที ขณะ ffmpeg มี progress
        A->>DB: extend lease WHERE attempt = 1
        A->>Q: ChangeMessageVisibility 3m
    end
    Note over A: OOM kill / spot reclaim ที่ 60%
    Note over Q,DB: ไม่มี heartbeat → lease และ visibility หมดภายใน 3 นาที
    Q->>B: redeliver, ApproximateReceiveCount = 2
    B->>DB: claim WHERE lease_until < now() → attempt 2
    B->>S3: PUT renditions/v9/720p/a2/
    B->>DB: DONE WHERE attempt = 2 → 1 row
    B->>Q: DeleteMessage
    Note over A,B: งานไม่หาย เสียเวลาไปแค่ส่วนที่ A ทำค้างไว้ + ไม่เกิน 3 นาที
RESULT

กำลังวาด diagram…

Poison message และ DLQ

Worker จัดการ error ที่ตัวเองเห็นได้ (permanent → FAILED ทันที) แต่ถ้า pod ตายทุกครั้ง (OOM) worker ไม่มีโอกาสบันทึกอะไรเลย ต้องพึ่ง maxReceiveCount ของคิว ให้ SQS ย้าย message ไป DLQ แล้ว DLQ handler ปิดงานเป็น FAILED

queues.tf
# Terraform: คิวหลัก + DLQ (poison message หลุดไปที่นี่หลังรับครบ 4 ครั้ง)
resource "aws_sqs_queue" "transcode_dlq" {
  name                      = "transcode-dlq"
  message_retention_seconds = 1209600 # 14 วัน (สูงสุด) ต้องนานกว่าคิวหลัก
}

resource "aws_sqs_queue" "transcode" {
  name                       = "transcode-jobs"
  visibility_timeout_seconds = 180    # = leaseTTL, worker ต่อเองด้วย heartbeat
  receive_wait_time_seconds  = 20     # long polling
  message_retention_seconds  = 345600 # 4 วัน

  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.transcode_dlq.arn
    maxReceiveCount     = 4 # ทุก receive นับ รวมถึงครั้งที่ worker ตาย/ถูก spot reclaim
  })
}
dlq.go
// DLQ handler: จับเคสที่ worker ไม่มีโอกาสบันทึกเอง เช่น ffmpeg OOM ฆ่า pod ทุกครั้ง
func (d *DLQHandler) Handle(ctx context.Context, msg JobMessage) error {
	return pgx.BeginFunc(ctx, d.db, func(tx pgx.Tx) error {
		var videoID uuid.UUID
		err := tx.QueryRow(ctx, `
			UPDATE transcode_jobs
			SET status = 'FAILED', lease_until = NULL, finished_at = now(),
			    last_error = coalesce(last_error, '') || ' | moved to DLQ'
			WHERE id = $1 AND status IN ('QUEUED', 'RUNNING')
			RETURNING video_id`, msg.JobID).Scan(&videoID)
		if errors.Is(err, pgx.ErrNoRows) {
			return nil // job จบไปแล้ว (DONE) → แค่ลบ message
		}
		if err != nil {
			return err
		}
		if _, err := tx.Exec(ctx, `
			UPDATE videos SET status = 'FAILED', updated_at = now()
			WHERE id = $1 AND status = 'PROCESSING'`, videoID); err != nil {
			return err
		}
		d.metrics.DLQJobs.Inc() // alert: > 0 ใน 15 นาที → on-call ดู last_error
		return enqueue(ctx, tx, videoID, "VideoFailed", map[string]any{"jobId": msg.JobID})
	})
}

Autoscaling ตาม backlog

scaledobject.yaml
# KEDA: scale ตามจำนวน message (visible + in-flight) = 1 message ต่อ pod
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: transcode-worker
spec:
  scaleTargetRef:
    name: transcode-worker
  minReplicaCount: 20      # กลางคืนยังมีงานไหลเข้า
  maxReplicaCount: 800     # เพดานงบ: เกินนี้ให้คิวดูดซับ
  cooldownPeriod: 600      # ไม่ scale-in ถี่จนฆ่างานที่ทำอยู่
  triggers:
    - type: aws-sqs-queue
      metadata:
        queueURL: https://sqs.ap-southeast-1.amazonaws.com/123456789012/transcode-jobs
        queueLength: "1"
        awsRegion: ap-southeast-1
        scaleOnInFlight: "true"
      authenticationRef:
        name: keda-aws-credentials
ข้อดี
  • Component น้อย: SQS + DLQ + PostgreSQL ที่ทีมรู้จักอยู่แล้ว
  • Worker stateless จึง scale ตามความยาวคิวและใช้ spot ได้
  • Failure mode ชัด อธิบายได้ทีละบรรทัด
  • คิวเป็น buffer ตอน burst โดยธรรมชาติ
ข้อแลกเปลี่ยน
  • Fan-in, retry และ state ต้องเขียนเองใน DB
  • Worker ตาย = เสียงานทั้ง rendition (สูงสุด ~30 นาที)
  • ต้องออกแบบ heartbeat, fencing และ DLQ ให้ถูกเอง

05แนวทาง B: Workflow Orchestrator (Temporal / Step Functions)

ให้ orchestrator จัดการ DAG ของงาน (probe → transcode ×4 → thumbnail → publish) พร้อม retry, timeout และ state ให้ในตัว

เหมาะเมื่อ

Pipeline หลายขั้นที่ขยายต่อเรื่อยๆ (moderation, DRM, subtitle, thumbnail) ต้องรอคนหรือรอระบบภายนอก และอยากได้ retry/timeout/ประวัติการรันจาก platform

ไม่เหมาะเมื่อ

ทีมยังไม่มีประสบการณ์ดูแล Temporal (หรือไม่อยากผูกกับ Step Functions) และ pipeline มีแค่ 2–3 ขั้น ความซับซ้อนที่เพิ่มขึ้นจะไม่คุ้ม

Architecture

แทนที่ PostgreSQL + SQS จะเป็นคนจำ state เอง ให้ Temporal เก็บ event history ของ workflow แต่ละวิดีโอ ใช้ video-{id} เป็น workflow ID จึงสั่งเริ่มซ้ำแล้วไม่เกิด 2 pipeline งาน transcode เป็น activity บน task queue แยก ทำให้ scale เครื่อง CPU แยกจากตัวที่รัน workflow ได้

CODEarchitecture-b.mmd
flowchart LR
    U[Client] -->|presigned PUT| S3R[(S3 raw)]
    U --> API[Video API]
    API --> PG[(PostgreSQL<br/>videos read model)]
    API -->|StartWorkflow id = video-v9| T[Temporal Service<br/>event history]
    T --> WQ[[task queue<br/>video-pipeline]]
    T --> TQ[[task queue<br/>transcode-cpu]]
    WQ --> WW[Workflow Worker<br/>deterministic code]
    TQ --> AW[Activity Workers<br/>ffmpeg + heartbeat]
    AW --> S3R
    AW --> S3O[(S3 renditions)]
    AW --> RD[(Redis progress)]
    AW --> PG
    API --> RD
RESULT

กำลังวาด diagram…

workflow.go
package pipeline

import (
	"time"

	"go.temporal.io/sdk/temporal"
	"go.temporal.io/sdk/workflow"
)

type VideoInput struct {
	VideoID   string
	SourceKey string
}

// Workflow code ต้อง deterministic: ห้ามเรียก I/O, time.Now, rand ตรงๆ
// ทุกอย่างที่แตะโลกภายนอกเป็น activity และ Temporal replay จาก event history ได้
func VideoWorkflow(ctx workflow.Context, in VideoInput) error {
	var a *Activities // reference method เพื่อ type-safe (ไม่ถูกเรียกใน workflow)

	short := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
		StartToCloseTimeout: 5 * time.Minute,
		RetryPolicy:         &temporal.RetryPolicy{MaximumAttempts: 5},
	})
	var meta ProbeResult
	if err := workflow.ExecuteActivity(short, a.Probe, in).Get(ctx, &meta); err != nil {
		return markFailed(short, in.VideoID, err)
	}

	transcode := workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
		TaskQueue:           "transcode-cpu",
		StartToCloseTimeout: 45 * time.Minute, // งานยาวสุด 30 นาที + เผื่อ
		HeartbeatTimeout:    2 * time.Minute,  // worker ตาย/ค้าง → รู้ภายใน 2 นาที
		RetryPolicy: &temporal.RetryPolicy{
			InitialInterval:        30 * time.Second,
			BackoffCoefficient:     2.0,
			MaximumInterval:        10 * time.Minute,
			MaximumAttempts:        4,
			NonRetryableErrorTypes: []string{"InvalidInput"},
		},
	})

	// fan-out: สั่ง 4 activity พร้อมกัน แล้ว fan-in ด้วย Future
	fanCtx, cancelAll := workflow.WithCancel(transcode)
	futures := make([]workflow.Future, len(meta.Renditions))
	for i, r := range meta.Renditions {
		futures[i] = workflow.ExecuteActivity(fanCtx, a.Transcode, TranscodeInput{
			VideoID: in.VideoID, SourceKey: in.SourceKey, Rendition: r, DurationMs: meta.DurationMs,
		})
	}
	outputs := make([]RenditionOutput, len(futures))
	for i, f := range futures {
		if err := f.Get(ctx, &outputs[i]); err != nil {
			cancelAll() // rendition หนึ่ง fail ถาวร → หยุดตัวที่เหลือ ไม่เผา CPU ต่อ
			return markFailed(short, in.VideoID, err)
		}
	}

	return workflow.ExecuteActivity(short, a.Publish, in.VideoID, outputs).Get(ctx, nil)
}

func markFailed(ctx workflow.Context, videoID string, cause error) error {
	var a *Activities
	_ = workflow.ExecuteActivity(ctx, a.MarkFailed, videoID, cause.Error()).Get(ctx, nil)
	return cause
}
activity.go
// import: go.temporal.io/sdk/{activity,client,temporal},
//         enumspb "go.temporal.io/api/enums/v1", "go.temporal.io/api/serviceerror"

// Activity: โค้ดธรรมดา ทำ I/O ได้ แต่ต้อง idempotent เพราะอาจถูก retry
func (a *Activities) Transcode(ctx context.Context, in TranscodeInput) (RenditionOutput, error) {
	info := activity.GetInfo(ctx)
	// prefix ผูกกับ attempt → attempt ที่ตายไปแล้วไม่ทับผลของ attempt ใหม่
	prefix := fmt.Sprintf("renditions/%s/%s/a%d/", in.VideoID, in.Rendition, info.Attempt)

	err := a.tc.RunTo(ctx, in, prefix, func(pct float64) {
		// heartbeat ต้องมาจาก progress จริง: ffmpeg ค้าง → ไม่มี heartbeat → timeout → retry
		// และ activity จะรู้ว่าถูก cancel ก็ผ่าน heartbeat เท่านั้น (ctx.Done)
		activity.RecordHeartbeat(ctx, pct)
		a.progress.Publish(ctx, in.VideoID, in.Rendition, pct) // UI ยังใช้ Redis เหมือนแนวทาง A
	})
	if errors.Is(err, ErrInvalidInput) {
		return RenditionOutput{}, temporal.NewNonRetryableApplicationError(
			"invalid input", "InvalidInput", err)
	}
	if err != nil {
		return RenditionOutput{}, err // retry ตาม RetryPolicy
	}
	return RenditionOutput{Rendition: in.Rendition, Prefix: prefix}, nil
}

// เริ่ม workflow: ใช้ videoID เป็น workflow ID → กดซ้ำ/relay ส่งซ้ำไม่เกิด 2 pipeline
func StartPipeline(ctx context.Context, c client.Client, in VideoInput) error {
	_, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
		ID:                                       "video-" + in.VideoID,
		TaskQueue:                                "video-pipeline",
		WorkflowIDReusePolicy:                    enumspb.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE,
		WorkflowExecutionErrorWhenAlreadyStarted: true,
	}, VideoWorkflow, in)
	var already *serviceerror.WorkflowExecutionAlreadyStarted
	if errors.As(err, &already) {
		return nil // เริ่มไปแล้ว = สำเร็จ (idempotent)
	}
	return err
}
CODEsequence-b.mmd
sequenceDiagram
    autonumber
    participant API as Video API
    participant T as Temporal
    participant WF as VideoWorkflow
    participant AW as Activity Workers

    API->>T: StartWorkflow id = video-v9
    T->>WF: run
    WF->>AW: Probe
    AW-->>WF: 1080p source, 12 นาที
    par fan-out
        WF->>AW: Transcode 1080p
    and
        WF->>AW: Transcode 720p
    and
        WF->>AW: Transcode 480p
    and
        WF->>AW: Transcode 360p
    end
    Note over AW: worker ที่ทำ 720p ตาย → ไม่มี heartbeat 2 นาที
    T->>AW: retry 720p attempt 2 บน worker อื่น
    AW-->>WF: ครบ 4 futures
    WF->>AW: Publish master.m3u8 + videos READY
RESULT

กำลังวาด diagram…

ข้อดี
  • Retry, timeout, heartbeat และ fan-in มีให้ในตัว
  • DAG อ่านได้เป็นโค้ด Go ธรรมดา ต่อขั้นใหม่ง่าย
  • มีประวัติทุก execution ใช้ debug และ replay
  • รอได้เป็นวันโดยไม่ถือ worker (signal/timer)
ข้อแลกเปลี่ยน
  • เพิ่ม platform ที่ต้องดูแล (Temporal cluster) หรือค่าใช้จ่าย cloud
  • Workflow code ต้อง deterministic ทีมต้องเรียนรู้ข้อจำกัด
  • Progress ที่ละเอียดยังต้องใช้ Redis แยก

06แนวทาง C: Chunked Parallel Transcoding

ตัดวิดีโอเป็นช่วงสั้นๆ แล้ว transcode แบบขนานก่อนนำมาต่อกัน ลดเวลาจากหลักสิบนาทีเหลือไม่กี่นาที แลกกับความซับซ้อนที่เพิ่มขึ้น

เหมาะเมื่อ

SLA จนดูได้ระดับนาที วิดีโอยาวเป็นชั่วโมง หรืออยากให้ worker ตายแล้วเสียงานน้อยที่สุด (เหมาะกับ spot)

ไม่เหมาะเมื่อ

SLA ยอมรอ 30 นาทีได้ วิดีโอส่วนใหญ่สั้น หรือต้องการคุณภาพ encode สูงสุด (2-pass ทั้งไฟล์) เพราะ overhead และรอยต่อ chunk ไม่คุ้ม

Architecture

วิดีโอ 12 นาทีตัดทุก 30 วินาทีได้ 24 chunk × 4 rendition = 96 task ถ้ามี worker ว่าง 96 ตัว แต่ละ task ใช้เวลาไม่ถึงนาที รวม split และ assemble แล้วเสร็จในไม่กี่นาที เคล็ดลับให้ต่อกันได้คือ: ตัดที่ keyframe ด้วย stream copy, encode ทุก chunk ด้วย setting และ GOP เดียวกัน และ encode audio แยกทั้งไฟล์ เพราะ AAC ที่ตัดเป็นท่อนจะมีช่องว่าง (priming samples) ที่รอยต่อ

CODEarchitecture-c.mmd
flowchart LR
    S3R[(S3 raw)] --> SP[Split Job<br/>stream copy ตาม keyframe]
    SP --> AUD[Audio Job<br/>encode ทั้งไฟล์ครั้งเดียว]
    SP -->|N chunks × 4 renditions| Q[[SQS chunk-tasks]]
    Q --> CW1[Chunk Worker]
    Q --> CW2[Chunk Worker]
    Q --> CW3[Chunk Worker ...]
    CW1 & CW2 & CW3 --> S3C[(S3 chunk outputs)]
    CW1 & CW2 & CW3 --> PG[(chunk_tasks<br/>rendition counters)]
    PG -->|chunks_done = total| AS[Assemble Job<br/>concat + mux audio + HLS]
    AUD --> AS
    S3C --> AS
    AS --> S3O[(S3 renditions)]
RESULT

กำลังวาด diagram…

split-assemble.sh
# 1) Audio: encode ทั้งไฟล์ครั้งเดียว (ตัด audio เป็นท่อนจะมีเสียงคลิก/ช่องว่างที่รอยต่อ)
ffmpeg -i source.mp4 -vn -c:a aac -b:a 128k -ac 2 audio.m4a

# 2) Video: ตัดที่ keyframe ด้วย stream copy (ไม่ decode จึงเสร็จในไม่กี่วินาที)
ffmpeg -i source.mp4 -map 0:v:0 -an -c:v copy \
  -f segment -segment_time 30 -reset_timestamps 1 chunk_%04d.mp4

# 3) Chunk task: ทุก chunk ใช้ setting เดียวกัน + keyframe ทุก 2 วินาที → ต่อกันได้ไม่สะดุด
ffmpeg -i chunk_0003.mp4 -vf scale=-2:720 -c:v libx264 -preset veryfast \
  -b:v 2800k -maxrate 3000k -bufsize 5600k \
  -force_key_frames "expr:gte(t,n_forced*2)" -sc_threshold 0 \
  out_720p_0003.mp4

# 4) Assemble: ต่อ chunk ด้วย concat demuxer (stream copy) + mux audio → HLS
printf "file '%s'\n" out_720p_*.mp4 > list.txt
ffmpeg -f concat -safe 0 -i list.txt -i audio.m4a -map 0:v -map 1:a -c copy \
  -f hls -hls_time 4 -hls_playlist_type vod \
  -hls_segment_filename 'seg_%05d.ts' index.m3u8

Fan-in 2 ชั้นแบบ idempotent

ใช้หลักการเดียวกับแนวทาง A แต่ลดระดับลงมาเป็น chunk: commit chunk ด้วย attempt แล้วเพิ่ม counter ของ rendition ใน statement เดียว ตัวที่ทำให้ counter เท่ากับ total เป็นคนสั่ง assemble และเมื่อ assemble เสร็จจะเพิ่ม counter ของ video ต่ออีกชั้น

chunks.sql
CREATE TABLE renditions (
  video_id     uuid NOT NULL,
  rendition    text NOT NULL,
  chunks_total int  NOT NULL,
  chunks_done  int  NOT NULL DEFAULT 0 CHECK (chunks_done <= chunks_total),
  PRIMARY KEY (video_id, rendition)
);

CREATE TABLE chunk_tasks (
  video_id    uuid NOT NULL,
  rendition   text NOT NULL,
  chunk_no    int  NOT NULL,
  status      text NOT NULL DEFAULT 'QUEUED',
  attempt     int  NOT NULL DEFAULT 0,
  lease_until timestamptz,
  output_key  text,
  PRIMARY KEY (video_id, rendition, chunk_no)
);

-- Commit chunk: fencing ด้วย attempt + นับ fan-in ใน statement เดียว
-- chunk ที่ commit ซ้ำ (message ซ้ำ / zombie) → CTE ได้ 0 row → counter ไม่ขยับ
WITH done AS (
  UPDATE chunk_tasks
  SET status = 'DONE', output_key = $5, lease_until = NULL
  WHERE video_id = $1 AND rendition = $2 AND chunk_no = $3
    AND attempt = $4 AND status = 'RUNNING'
  RETURNING video_id, rendition
)
UPDATE renditions r
SET chunks_done = r.chunks_done + 1
FROM done
WHERE r.video_id = done.video_id AND r.rendition = done.rendition
RETURNING r.chunks_done = r.chunks_total AS ready_to_assemble;
-- ready_to_assemble = true → INSERT outbox AssembleRequested ใน tx เดียวกัน
CODEsequence-c.mmd
sequenceDiagram
    autonumber
    participant SP as Split Job
    participant Q as SQS chunk-tasks
    participant W as Chunk Workers
    participant DB as PostgreSQL
    participant AS as Assemble Job

    SP->>DB: INSERT chunk_tasks 24 chunks × 4 renditions
    SP->>Q: enqueue 96 tasks ผ่าน outbox
    par ประมวลผลขนาน
        Q->>W: chunk 0003 / 720p
        W->>DB: commit WHERE attempt = n → chunks_done + 1
    and
        Q->>W: chunk 0017 / 1080p
        W->>DB: commit → chunks_done + 1
    end
    Note over W: worker ตาย → เสียแค่ chunk 30 วินาที visibility สั้นได้
    Note over DB: 720p chunks_done = 24 → outbox AssembleRequested
    DB-->>AS: assemble 720p
    AS->>AS: concat -c copy + mux audio → HLS
    AS->>DB: rendition DONE → videos.renditions_done + 1
RESULT

กำลังวาด diagram…

ข้อดี
  • เวลาจนดูได้ลดจาก 25 นาทีเหลือ 2–4 นาที
  • Worker ตายเสียแค่ chunk ~30 วินาที ไม่ต้องใช้ heartbeat ยาว
  • ใช้ worker จำนวนมากช่วยกันทำวิดีโอเดียวได้ (ใช้เครื่องได้เต็ม)
ข้อแลกเปลี่ยน
  • ซับซ้อนสุด: split, audio แยก, assemble และ fan-in 2 ชั้น
  • Rate control ทำทีละ chunk จึงคุม bitrate ทั้งไฟล์ได้ไม่ดีเท่า
  • จำนวน task และ S3 request เพิ่มหลายสิบเท่า

07Failure handling

ทุกแถวต้องตอบ 2 อย่าง: ระบบรู้ได้อย่างไร และ กลับสู่สถานะถูกต้องได้อย่างไร แถวที่มี (B) หรือ (C) ใช้เฉพาะแนวทางนั้น

สถานการณ์กลไกผลลัพธ์
Worker ตาย (OOM, spot reclaim) กลาง transcode

Heartbeat หยุด → visibility + lease หมดใน ≤ 3 นาที → worker อื่น claim attempt ใหม่

งานไม่หาย เริ่มใหม่ที่เครื่องอื่น

ffmpeg ค้างแต่ process ยังอยู่

Heartbeat ผูกกับ progress: ไม่ขยับ 5 นาที → kill + release

Retry แทนการต่อ lease ไปตลอดกาล

Zombie worker กลับมาหลัง lease หมด

Output แยก prefix ต่อ attempt + commit WHERE attempt = n

Zombie ได้ 0 row แล้วทิ้งผล

Crash หลัง commit ก่อน ack / SQS ส่งซ้ำ

Claim เจอ DONE → แค่ DeleteMessage

ไม่ transcode ซ้ำ counter ไม่นับซ้ำ

Poison file (เสียทุกครั้ง / OOM ทุกครั้ง)

Permanent error → FAILED ทันที, crash loop → maxReceiveCount 4 → DLQ

ไม่วนกิน CPU + alert + แจ้งผู้ใช้

S3 / network error ชั่วคราว

Release + backoff ด้วย ChangeMessageVisibility

Retry อัตโนมัติ

2 rendition สุดท้ายเสร็จพร้อมกัน

Counter UPDATE … RETURNING ภายใต้ row lock

Publish ครั้งเดียวพอดี

Commit job แล้วส่งเข้าคิวไม่สำเร็จ

Transactional outbox + reconciler หา job ค้าง

Job ไม่ค้าง QUEUED

Upload หลุดกลางทาง

Multipart: resume เฉพาะ part ที่ขาด + AbortIncompleteMultipartUpload

ไม่ต้องเริ่ม 2GB ใหม่ ไม่มีขยะค้าง

Redis (progress) ล่ม

Worker log แล้วทำต่อ, UI fallback poll GET /videos/{id}

เห็น progress หยาบลง job ไม่กระทบ

Upload พุ่ง 10 เท่า

คิวดูดซับ + autoscale ตาม backlog ถึงเพดาน + quota ต่อ user

รอนานขึ้น แต่ไม่ล่ม ไม่มีงานหาย

Activity worker ตาย (B)

HeartbeatTimeout 2 นาที → Temporal retry ตาม RetryPolicy

เหมือน A แต่ orchestrator จัดการให้

Chunk เดียว fail ซ้ำ / รอยต่อ chunk (C)

Retry เฉพาะ chunk, closed GOP เท่ากันทุก chunk, audio encode แยก

เสียงานน้อย ไม่มีภาพกระตุก/เสียงคลิก

08สรุปคำตอบใน 3–5 นาที

09ไฟล์คำตอบที่ส่ง: system-design.md

นี่คือ ไฟล์เดียวที่ส่งจริง เขียนตามแนวทาง A ครบ 13 หัวข้อ บนสุดมี TL;DR ให้ผู้ตรวจเห็นคำตอบภายใน 30 วินาที ใช้ปุ่มหัวข้อด้านบนกระโดดไปแต่ละส่วนได้ หรือดาวน์โหลดไปเปิดใน editor ที่แสดง Mermaid ได้ (GitHub, VS Code, mermaid.live)

สังเกตโครงสร้าง
  • TL;DR → requirement → architecture → data → flow → failure → trade-off
  • ทุกหัวข้อตอบคำถามเดียวกัน: "worker ตายตรงนี้แล้วเกิดอะไร"
  • ตัวเลข capacity ถูกใช้ตัดสินใจจริง (presigned, เพดาน worker)
ในห้องสอบ 60 นาที
  • ไม่ต้องยาวเท่านี้ ให้ความสำคัญกับหัวข้อ 1, 3, 5, 6, 9, 10, 11 และ 13
  • Code เขียนแค่ SQL claim/commit + heartbeat loop ก็พอ
  • ห้ามตัด sequence "worker ตายกลางทาง" และ failure matrix
system-design.md629 บรรทัด · 15 หัวข้อ · 7 Mermaid · 10 code block · 8 ตาราง
# System Design: Video Upload & Transcoding Pipeline > **โจทย์:** ผู้ใช้อัปโหลดวิดีโอไฟล์ละไม่เกิน 2GB ระบบต้อง transcode เป็น 4 ความละเอียด แต่ละงานใช้เวลา 5–30 นาที> worker อาจตายกลางทางได้ ผู้ใช้ต้องเห็นความคืบหน้า และระบบต้องรองรับช่วงที่มีคนอัปโหลดพร้อมกันจำนวนมาก ## สรุป (TL;DR) - **Invariant:** transcode job ทุกตัวต้องจบที่ `DONE` หรือ `FAILED` เสมอ (ไม่หาย) และมีผลลัพธ์ที่ถูก commit ได้ชุดเดียว (ไม่เสียจากการทำซ้ำ)- **Upload:** client อัปโหลดตรงเข้า S3 ด้วย **presigned multipart URL** ไฟล์ไม่ผ่าน API และ resume ทีละ part ได้- **Processing:** probe แล้ว fan-out เป็น 1 job ต่อ rendition ใน PostgreSQL → outbox → **SQS** → stateless worker (1 pod = 1 job)- **Worker ตาย:** visibility timeout 3 นาที + **heartbeat** ทุก 1 นาทีที่ต่อทั้ง SQS visibility และ DB lease ถ้า worker ตาย งานจะกลับเข้าคิวภายใน ≤ 3 นาที- **ทำซ้ำไม่เสีย:** `attempt` เป็น fencing token, output เขียนลง prefix ของแต่ละ attempt, commit ด้วย `WHERE attempt = n`, ack หลัง commit เท่านั้น- **Poison:** permanent error → `FAILED` ทันที, crash loop → `maxReceiveCount = 4` → DLQ → `FAILED` + alert- **Progress:** ffmpeg `-progress` → Redis `HSET` + `PUBLISH` → SSE (best effort ไม่ใช่ source of truth)- **Burst:** คิวดูดซับ worker autoscale ตาม backlog ต่อ worker (มีเพดานงบ) และรันบน spot ได้ --- ## 1. Requirements & Core Invariant ### Functional- อัปโหลดวิดีโอไม่เกิน **2GB** และ resume ได้เมื่อเน็ตหลุด- Transcode เป็น 4 ความละเอียด: **1080p, 720p, 480p, 360p** (HLS, ไม่ upscale เกิน source)- ผู้ใช้เห็น **progress** ของแต่ละวิดีโอแบบ near real-time และเห็นสถานะสุดท้าย (READY / FAILED)- เล่นวิดีโอแบบ adaptive bitrate ผ่าน CDN เมื่อพร้อม ### Non-functional- **งานไม่หาย** แม้ worker ตายกลางทาง ตรวจพบและทำต่อภายใน ≤ 3 นาที- **ทำซ้ำได้โดยผลไม่เสีย** (at-least-once + idempotent output) และ publish วิดีโอครั้งเดียว- รับ **burst** ของการอัปโหลดได้โดยไม่ล่ม (ยอมให้รอนานขึ้นได้)- SLA: p95 ตั้งแต่อัปโหลดเสร็จจนดูได้ ≤ 45 นาทีในเวลาปกติ- คุมต้นทุน compute ได้ และ observe ได้ว่ามีงานค้างหรือไม่ ### Core Invariant ```textสำหรับทุก transcode job (video_id, rendition):  1) ต้องจบที่ DONE หรือ FAILED เสมอ (ไม่หายเงียบ)  2) มีผลลัพธ์ที่ถูก commit ได้ชุดเดียว (ของ attempt ที่ชนะ)สำหรับทุก video:  3) READY ก็ต่อเมื่อทุก rendition ที่ต้องทำเป็น DONE และ publish ครั้งเดียว``` > สถานะของ job บังคับที่ **PostgreSQL** (`attempt` = fencing token)> SQS รับประกันแค่ at-least-once delivery จึง **ไม่ใช่** ผู้ตัดสินว่าใครเป็นเจ้าของงาน --- ## 2. Assumptions & Capacity Estimation | Assumption | ค่า ||---|---|| Upload ต่อวัน | 10,000 วิดีโอ || ขนาดเฉลี่ย / สูงสุด | 500MB (ยาว ~10 นาที, source 1080p) / 2GB || Peak hour | 3 เท่าของค่าเฉลี่ย ≈ 1,250 uploads/ชม. || เวลา transcode ต่อ rendition (1 worker = 8 vCPU) | 1080p ~25, 720p ~15, 480p ~8, 360p ~5 นาที || Storage | S3 (raw + renditions), CDN หน้า renditions | **ประมาณการ:**- **Ingress ตอน peak:** 1,250 × 0.5GB / 3,600s ≈ **174MB/s (~1.4 Gbps)** → ห้ามผ่าน API server ต้องใช้ **presigned URL** ตรงเข้า S3- **Compute ต่อวิดีโอ:** 25 + 15 + 8 + 5 ≈ **50 worker-minutes**  - ทั้งวัน: 10,000 × 50 = 500,000 worker-minutes ≈ **347 worker** ทำงานตลอด 24 ชม.  - Peak hour: 1,250 × 50 = 62,500 worker-minutes/ชม. ≈ **1,040 worker** ถึงจะไม่มี backlog  - → ต้อง **autoscale** (min 20 ถึง max 800) ถ้าเกินเพดาน ให้คิวรับไว้แล้วระบายหลัง peak (แลก latency กับเงิน)- **Storage:** source 5TB/วัน + renditions ~7.5TB/วัน (bitrate รวม ~10 Mbps × 10 นาที ≈ 750MB) ≈ **375TB/เดือน** → ต้องมี lifecycle policy- **DB write:** heartbeat 1 ครั้ง/นาทีต่อ job ที่รันอยู่ ~1,000 job ≈ 17 writes/s และ progress ไปที่ Redis (~500 msg/s) → PostgreSQL ตัวเดียวรับได้สบาย --- ## 3. High-level Architecture ```mermaidflowchart LR    U[Client<br/>Web / Mobile] -->|1 create upload| API[Video API<br/>stateless]    U -->|2 PUT parts ตรง| S3R[(S3 raw bucket)]    U -->|3 complete| API    U -. SSE progress .-> API    API --> PG[(PostgreSQL<br/>videos · jobs · outbox)]    PG -.outbox.-> RELAY[Outbox Relay]    RELAY --> QP[[SQS probe-jobs]]    QP --> PW[Probe Worker<br/>ffprobe + fan-out]    PW --> PG    RELAY --> QT[[SQS transcode-jobs]]    QT --> TW[Transcode Workers<br/>1 job ต่อ pod · spot]    QT -. maxReceiveCount .-> DLQ[[transcode-dlq]]    DLQ --> DH[DLQ Handler<br/>FAILED + alert]    DH --> PG    TW --> S3R    TW --> S3O[(S3 renditions<br/>HLS)]    TW --> PG    TW --> RD[(Redis<br/>progress pub/sub)]    API --> RD    RELAY --> PUB[Publisher<br/>master.m3u8]    PUB --> S3O    S3O --> CDN[CDN] --> U    AS[Autoscaler<br/>backlog per worker] -. scale .-> TW``` **อธิบายสั้นๆ:**- **Ingest:** API ออก presigned URL และปิด upload เท่านั้น ไฟล์ขนาดใหญ่วิ่งตรงเข้า S3- **Processing:** PostgreSQL เก็บสถานะ job ส่วน SQS เป็นแค่ "กริ่ง" ที่ปลุก worker การส่งงานเข้าคิวผ่าน **transactional outbox** จึงไม่มี dual write- **Delivery:** publisher สร้าง master playlist จาก output ที่ commit แล้ว และเสิร์ฟผ่าน CDN --- ## 4. Component Responsibilities | Component | หน้าที่ | Stateful? | ถ้าล่ม ||---|---|---|---|| Video API | สร้าง upload, presign, complete, อ่านสถานะ, SSE | ไม่ | Replica อื่นรับแทน upload ที่กำลังส่งเข้า S3 ไม่กระทบ client retry complete ได้ (idempotent) || S3 (raw / renditions) | เก็บไฟล์ต้นฉบับและ HLS output | ใช่ (durable) | Managed ความทนทานสูง ถ้า error ชั่วคราว worker retry ด้วย backoff || PostgreSQL | Source of truth ของ video/job, outbox | ใช่ | Failover ไป standby ระหว่างนั้น claim/commit ไม่ได้ worker ไม่ ack งานจึงกลับเข้าคิวเอง || Outbox Relay | ส่ง event จาก outbox เข้า SQS | ไม่ | Event ค้างในตาราง ส่งต่อเมื่อกลับมา (at-least-once) || SQS transcode-jobs | ส่งงานให้ worker + visibility timeout | ใช่ (managed) | Worker รอ receive งานไม่หายเพราะอยู่ใน DB reconciler enqueue ใหม่ได้ || Probe Worker | ffprobe, ตัดสิน rendition, fan-out | ไม่ | Message กลับเข้าคิว fan-out ซ้ำได้เพราะมี UNIQUE || Transcode Worker | claim → ffmpeg → upload → commit → ack | ไม่ (scratch disk ชั่วคราว) | Heartbeat หยุด → lease หมด → worker อื่นทำต่อ (หัวข้อ 9) || DLQ + Handler | รับ poison message, mark FAILED, alert | ไม่ | Message รออยู่ใน DLQ 14 วัน ประมวลผลต่อเมื่อกลับมา || Publisher | เขียน master.m3u8 แล้วเปลี่ยน video → READY | ไม่ | Video ค้าง PROCESSING นานขึ้น event ยังอยู่ในคิว || Redis | Progress snapshot + pub/sub | ใช่ (สร้างใหม่ได้) | Progress หยุด แต่ job เดินต่อ UI fallback poll `GET /videos/{id}` || Autoscaler (KEDA) | Scale worker ตาม backlog | ไม่ | จำนวน worker ค้างที่ค่าเดิม คิวยาวขึ้นแต่ไม่มีงานหาย | --- ## 5. Data Model ```mermaiderDiagram    VIDEO ||--o{ TRANSCODE_JOB : "fan-out"    VIDEO ||--o{ OUTBOX : emits     VIDEO {        uuid id PK        uuid owner_id        text status "UPLOADING|UPLOADED|PROCESSING|READY|FAILED"        text source_key        text s3_upload_id        bigint size_bytes        bigint duration_ms        int renditions_total        int renditions_done    }    TRANSCODE_JOB {        uuid id PK        uuid video_id FK        text rendition "UNIQUE(video_id, rendition)"        text status "QUEUED|RUNNING|DONE|FAILED"        int attempt "fencing token"        text worker_id        timestamptz lease_until        text output_prefix "ผลของ attempt ที่ชนะ"    }    OUTBOX {        bigint id PK        uuid aggregate_id        text event_type        jsonb payload    }``` ```sqlCREATE TABLE videos (  id               uuid PRIMARY KEY,  owner_id         uuid        NOT NULL,  status           text        NOT NULL DEFAULT 'UPLOADING'                   CHECK (status IN ('UPLOADING','UPLOADED','PROCESSING','READY','FAILED')),  source_key       text        NOT NULL,  s3_upload_id     text,  size_bytes       bigint      CHECK (size_bytes <= 2147483648),  duration_ms      bigint,  renditions_total int         NOT NULL DEFAULT 0,  renditions_done  int         NOT NULL DEFAULT 0,  created_at       timestamptz NOT NULL DEFAULT now(),  updated_at       timestamptz NOT NULL DEFAULT now(),  CHECK (renditions_done <= renditions_total)); CREATE TABLE transcode_jobs (  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),  video_id      uuid NOT NULL REFERENCES videos (id),  rendition     text NOT NULL CHECK (rendition IN ('1080p','720p','480p','360p')),  status        text NOT NULL DEFAULT 'QUEUED'                CHECK (status IN ('QUEUED','RUNNING','DONE','FAILED')),  attempt       int  NOT NULL DEFAULT 0,       -- fencing token: +1 ทุกครั้งที่ claim  worker_id     text,  lease_until   timestamptz,  output_prefix text,                          -- renditions/{video}/{rendition}/a{attempt}/  last_error    text,  started_at    timestamptz,  finished_at   timestamptz,  updated_at    timestamptz NOT NULL DEFAULT now(),  UNIQUE (video_id, rendition),                -- fan-out ซ้ำก็ไม่เกิด job ซ้ำ  CHECK (status <> 'DONE' OR output_prefix IS NOT NULL));CREATE INDEX transcode_jobs_running_lease ON transcode_jobs (lease_until) WHERE status = 'RUNNING'; CREATE TABLE outbox (  id           bigserial PRIMARY KEY,  aggregate_id uuid        NOT NULL,  event_type   text        NOT NULL,  payload      jsonb       NOT NULL,  created_at   timestamptz NOT NULL DEFAULT now(),  published_at timestamptz);``` **Guard ที่ทำให้ invariant จริง:**1. `UNIQUE (video_id, rendition)` → fan-out ซ้ำไม่สร้าง job ซ้ำ2. `attempt` + `WHERE attempt = n` → worker ที่เสีย lease commit ไม่ได้3. `renditions_done <= renditions_total` + counter ภายใต้ row lock → publish ครั้งเดียว --- ## 6. Job / Video Lifecycle ```mermaidstateDiagram-v2    [*] --> QUEUED: probe fan-out    QUEUED --> RUNNING: claim (attempt+1, lease 3m)    RUNNING --> RUNNING: heartbeat ต่อ lease ทุก 1m    RUNNING --> DONE: commit WHERE attempt = n    RUNNING --> QUEUED: transient error / SIGTERM → release    RUNNING --> FAILED: permanent error / ครบ maxReceiveCount    QUEUED --> FAILED: DLQ handler    FAILED --> QUEUED: admin redrive หลังแก้ bug    DONE --> [*]``` ```mermaidstateDiagram-v2    [*] --> UPLOADING: POST /videos    UPLOADING --> UPLOADED: complete + HeadObject ≤ 2GB    UPLOADING --> FAILED: ค้างเกิน 24 ชม. → abort multipart    UPLOADED --> PROCESSING: ffprobe ผ่าน → fan-out    UPLOADED --> FAILED: ไม่ใช่ไฟล์วิดีโอ    PROCESSING --> READY: ครบทุก rendition + master.m3u8    PROCESSING --> FAILED: job ใด FAILED ถาวร    READY --> [*]``` **ประเด็นที่ต้องเขียนอธิบาย:**- `RUNNING` มี lease เสมอ worker ที่ตายจะไม่ถือ job ไว้ตลอดไป เพราะ `lease_until` หมดแล้ว worker อื่น claim ได้- `READY` เกิดหลัง master playlist ถูกเขียนแล้วเท่านั้น ผู้ใช้กดเล่นแล้วจะไม่เจอ 404- Rendition ที่เกิน source (เช่น source 720p) ไม่สร้าง job เลย `renditions_total` จึงเป็น 3 --- ## 7. API Design | Method | Path | Idempotent ด้วย | ผลลัพธ์ ||---|---|---|---|| `POST` | `/videos` | Header `Idempotency-Key` | `201` videoId + presigned part URLs || `GET` | `/videos/{id}/upload` | – (read) | Part ที่อัปแล้ว (ListParts) + URL ใหม่ของ part ที่ขาด || `POST` | `/videos/{id}/complete` | สถานะ video (`UPLOADING` เท่านั้น) | `202` เริ่ม processing || `GET` | `/videos/{id}` | – | สถานะ + rendition ที่เสร็จแล้ว (ใช้ poll เป็น fallback) || `GET` | `/videos/{id}/events` | – | SSE: `snapshot`, `progress`, `status` || `GET` | `/videos/{id}/playback` | – | URL ของ master.m3u8 บน CDN (signed) | ```httpPOST /videosAuthorization: Bearer <token>Idempotency-Key: 0b7c5a52-3f0e-4a5e-9d59-2f1f3b6e8a10Content-Type: application/json { "filename": "trip.mp4", "size": 1450000000, "contentType": "video/mp4" }``` ```jsonHTTP/1.1 201 Created{  "videoId": "9d1e...",  "partSize": 67108864,  "parts": [    { "partNumber": 1, "url": "https://raw-bucket.s3...&X-Amz-Signature=..." },    { "partNumber": 2, "url": "https://raw-bucket.s3...&X-Amz-Signature=..." }  ]}``` --- ## 8. Data Flow: Happy Path ```mermaidsequenceDiagram    autonumber    actor U as User    participant API as Video API    participant S3 as S3    participant DB as PostgreSQL    participant Q as SQS    participant W as Transcode Worker    participant R as Redis     U->>API: POST /videos size 1.4GB    API->>S3: CreateMultipartUpload    API->>DB: INSERT video UPLOADING    API-->>U: videoId + 22 presigned part URLs    U->>S3: PUT part 1..22 ขนาน 4 ตัว    U->>API: POST /videos/v9/complete ETags    API->>S3: CompleteMultipartUpload + HeadObject    API->>DB: video UPLOADED + outbox VideoUploaded    Note over DB,Q: relay → probe worker → ffprobe → fan-out 4 jobs + outbox    Q->>W: job 720p    W->>DB: claim → RUNNING attempt 1    loop ทุก 2 วินาที        W->>R: HSET + PUBLISH 720p 42%        R-->>U: SSE progress    end    W->>S3: PUT renditions/v9/720p/a1/    W->>DB: DONE WHERE attempt 1 + renditions_done 4 of 4    W->>Q: DeleteMessage    Note over DB,S3: publisher เขียน master.m3u8 → video READY    R-->>U: SSE status READY``` **Fan-out ที่ probe worker (idempotent):** ```sqlWITH v AS (  UPDATE videos  SET status = 'PROCESSING', duration_ms = $2,      renditions_total = cardinality($3::text[]), updated_at = now()  WHERE id = $1 AND status = 'UPLOADED'  RETURNING id), jobs AS (  INSERT INTO transcode_jobs (video_id, rendition)  SELECT v.id, r FROM v, unnest($3::text[]) AS r  ON CONFLICT (video_id, rendition) DO NOTHING  RETURNING id)INSERT INTO outbox (aggregate_id, event_type, payload)SELECT $1, 'TranscodeRequested', jsonb_build_object('jobId', jobs.id) FROM jobs;``` --- ## 9. Worker Lease, Heartbeat & Fan-in ### 9.1 ทำไมวิธีง่ายๆ ถึงพัง | วิธี | ผลเมื่อ worker ตาย / งานยาว ||---|---|| Ack ทันทีที่รับ message | Worker ตาย → งานหายเงียบ video ค้าง PROCESSING ตลอดไป || Visibility timeout ยาว 45 นาทีตายตัว | Worker ตายนาทีที่ 1 → ต้องรอ 44 นาทีกว่างานจะกลับเข้าคิว || Visibility timeout สั้น 5 นาที ไม่มี heartbeat | งาน 25 นาทีโผล่กลับเข้าคิวระหว่างทำ → worker 5 ตัวทำงานเดียวกัน | ### 9.2 วิธีที่เลือก: lease สั้น + heartbeat + fencing 1. **Receive** ด้วย visibility 3 นาที (`MaxNumberOfMessages = 1`, long polling 20s)2. **Claim** ใน DB แบบ atomic → ได้ `attempt` ใหม่3. **Heartbeat** ทุก 1 นาที: ต่อ `lease_until` (`WHERE attempt = n`) และ `ChangeMessageVisibility` อีก 3 นาที   - Heartbeat ผูกกับ **progress จริง** ถ้า ffmpeg ไม่ขยับ 5 นาที → kill แล้ว release (กัน ffmpeg ค้าง)   - ถ้าต่อ lease ได้ 0 row → มีคน claim attempt ใหม่ไปแล้ว → หยุดทันที4. **Output** เขียนลง `renditions/{video}/{rendition}/a{attempt}/`5. **Commit** `DONE WHERE attempt = n` + fan-in counter ใน transaction เดียว6. **DeleteMessage หลัง commit เท่านั้น** ```sql-- claim: QUEUED หรือ RUNNING ที่ lease หมด (worker เดิมตาย)UPDATE transcode_jobs jSET status = 'RUNNING', attempt = j.attempt + 1, worker_id = $2,    lease_until = now() + interval '3 minutes', started_at = now(), updated_at = now()FROM videos vWHERE j.id = $1 AND v.id = j.video_id  AND (j.status = 'QUEUED' OR (j.status = 'RUNNING' AND j.lease_until < now()))RETURNING j.video_id, j.rendition, j.attempt, v.source_key, v.duration_ms;-- 0 row → ถ้า DONE/FAILED: แค่ ack | ถ้า RUNNING (lease ยังไม่หมด): ChangeMessageVisibility แล้วค่อยกลับมาดู``` ```go// ส่วนหลักของ worker (ตัด error handling บางส่วนเพื่อความกระชับ)func (w *Worker) handle(ctx context.Context, m types.Message) {	var msg JobMessage	if err := json.Unmarshal([]byte(aws.ToString(m.Body)), &msg); err != nil {		return // malformed → ไม่ ack ปล่อยให้ไป DLQ	}	receives, _ := strconv.Atoi(m.Attributes["ApproximateReceiveCount"]) 	claim, err := w.claim(ctx, msg.JobID)	switch {	case errors.Is(err, errTerminal):		w.ack(ctx, m) // ซ้ำ / crash หลัง commit		return	case errors.Is(err, errLeasedByOther):		w.visibleAfter(ctx, m, leaseTTL)		return	case err != nil:		return // DB ล่ม → ไม่ ack	} 	jobCtx, cancel := context.WithCancelCause(ctx)	hb := w.startHeartbeat(jobCtx, cancel, m.ReceiptHandle, claim) // ต่อ DB lease + SQS visibility	prefix, runErr := w.tc.Run(jobCtx, claim, func(pct float64) {		hb.touch()                            // มี progress จริง		w.progress.Report(jobCtx, claim, pct) // Redis HSET + PUBLISH (throttle 2s)	})	cancel(nil)	hb.wait() 	switch {	case errors.Is(context.Cause(jobCtx), errLostLease):		return // ถูก fence แล้ว ทิ้งผล	case ctx.Err() != nil:		w.release(context.WithoutCancel(ctx), m, claim, "shutdown", 0) // SIGTERM / spot		return	case runErr != nil && (isPermanent(runErr) || receives >= maxReceiveCount):		if w.fail(ctx, claim, runErr) == nil {			w.ack(ctx, m)		}		return	case runErr != nil:		w.release(ctx, m, claim, runErr.Error(), backoff(receives))		return	}	if err := w.commit(ctx, claim, prefix); err != nil {		return // lost lease หรือ DB error → ไม่ ack	}	w.ack(ctx, m)}``` ### 9.3 Fan-in: publish ครั้งเดียว ห้ามใช้ `SELECT count(*) ... WHERE status = 'DONE'` ใน transaction ของตัวเอง เพราะถ้า 2 rendition สุดท้าย commit พร้อมกันแต่ละฝั่งจะไม่เห็นงานที่อีกฝั่งยังไม่ commit (READ COMMITTED) จึงเห็น 3/4 ทั้งคู่ และไม่มีใคร publish ```gofunc (w *Worker) commit(ctx context.Context, c Claim, prefix string) error {	return pgx.BeginFunc(ctx, w.db, func(tx pgx.Tx) error {		tag, err := tx.Exec(ctx, `			UPDATE transcode_jobs			SET status = 'DONE', output_prefix = $3, lease_until = NULL, finished_at = now()			WHERE id = $1 AND attempt = $2 AND status = 'RUNNING'`,			c.JobID, c.Attempt, prefix)		if err != nil {			return err		}		if tag.RowsAffected() == 0 {			return errLostLease		}		// row lock ของ video เรียงลำดับ commit ที่มาพร้อมกัน → เห็น done == total ได้ตัวเดียว		var done, total int		if err := tx.QueryRow(ctx, `			UPDATE videos SET renditions_done = renditions_done + 1, updated_at = now()			WHERE id = $1 RETURNING renditions_done, renditions_total`,			c.VideoID).Scan(&done, &total); err != nil {			return err		}		if done < total {			return nil		}		return enqueue(ctx, tx, c.VideoID, "PublishRequested", map[string]any{"videoId": c.VideoID})	})}``` Publisher อ่าน `output_prefix` ของทุก job แล้ว `PutObject master.m3u8` (เนื้อหาได้มาจาก DB ล้วนๆ จึง PUT ซ้ำได้)จากนั้น `UPDATE videos SET status = 'READY' WHERE id = $1 AND status = 'PROCESSING'` + outbox `VideoReady` --- ## 10. Idempotency & Retry | จุด | ทำซ้ำได้เพราะ ||---|---|| `POST /videos` | `Idempotency-Key` → คืน videoId และ upload เดิม || `POST /videos/{id}/complete` | ทำเฉพาะเมื่อ `status = 'UPLOADING'` และ `NoSuchUpload` = complete ไปแล้ว || Probe / fan-out | `WHERE status = 'UPLOADED'` + `UNIQUE (video_id, rendition)` || Claim | Atomic UPDATE + ตรวจ lease → รับ message ซ้ำก็ไม่มีสองคนถือ lease พร้อมกัน || Transcode output | Key ผูกกับ `(video, rendition, attempt)` → ไม่ทับผลของ attempt อื่น || Commit | `WHERE attempt = n AND status = 'RUNNING'` → commit ได้ครั้งเดียว || Fan-in counter | ขยับเฉพาะใน tx ที่เปลี่ยน RUNNING → DONE ได้จริง || Publish | Master playlist มาจากข้อมูลใน DB ล้วน + `WHERE status = 'PROCESSING'` || Consumer ของ outbox | At-least-once → ทุก handler ข้างบนต้อง idempotent (ซึ่งเป็นแล้ว) | **Retry policy ของ transcode:**- **Permanent** (`Invalid data found when processing input`, `moov atom not found`, ffprobe บอกว่าไม่ใช่วิดีโอ) → `FAILED` ทันที ไม่ retry- **Transient** (S3 5xx, disk เต็ม, OOM, ffmpeg ค้าง) → release + `ChangeMessageVisibility` เป็น backoff (30s, 60s, 120s ...)- **Crash loop** (pod ตายทุกครั้งจนไม่มีโอกาสบันทึก) → `maxReceiveCount = 4` → DLQ → DLQ handler mark `FAILED` ```hclresource "aws_sqs_queue" "transcode" {  name                       = "transcode-jobs"  visibility_timeout_seconds = 180  receive_wait_time_seconds  = 20  message_retention_seconds  = 345600  redrive_policy = jsonencode({    deadLetterTargetArn = aws_sqs_queue.transcode_dlq.arn    maxReceiveCount     = 4  })}``` **ฝั่ง client:** อัปโหลดทีละ part (64MB) พร้อมกัน 4 part ถ้า part ไหน fail จะ retry เฉพาะ part นั้นด้วย backoff + jitterถ้า presigned URL หมดอายุ (403) หรือ refresh หน้า ให้เรียก `GET /videos/{id}/upload` เพื่อ resume เฉพาะ part ที่ขาด --- ## 11. Failure Handling ### 11.1 Failure Matrix | # | สถานการณ์ | ความเสี่ยง | กลไกที่ป้องกัน | ผลลัพธ์ ||---|---|---|---|---|| F1 | Worker ตาย (OOM, spot reclaim) กลาง transcode | งานหาย | ไม่ ack ก่อน commit + heartbeat หยุด → visibility/lease หมด ≤ 3 นาที | Worker อื่น claim attempt ใหม่ || F2 | ffmpeg ค้าง แต่ process ยังอยู่ | Heartbeat ต่อ lease ตลอดไป | Heartbeat ผูกกับ progress: ไม่ขยับ 5 นาที → kill + release | Retry บนเครื่องอื่น || F3 | Worker ถูก partition จน lease หมด แล้วกลับมา (zombie) | ผลเขียนทับ / นับ fan-in ซ้ำ | Prefix ต่อ attempt + commit `WHERE attempt = n` | Zombie ได้ 0 row แล้วทิ้งผล || F4 | Crash หลัง commit ก่อน DeleteMessage | Transcode ซ้ำ | Claim เจอ `DONE` → ack | ไม่ทำซ้ำ || F5 | SQS ส่ง message ซ้ำ (at-least-once) | สองคนทำพร้อมกัน | Claim atomic + lease | คนที่สองได้ 0 row แล้วรอดูใหม่ || F6 | ไฟล์เสีย (permanent error) | Retry วนเผา CPU | ตรวจ error → `FAILED` + ack | แจ้งผู้ใช้ทันที || F7 | Poison ที่ทำให้ pod ตายทุกครั้ง | Crash loop ไม่จบ | `maxReceiveCount = 4` → DLQ → handler | `FAILED` + alert on-call || F8 | S3 / network error ชั่วคราว | Job fail โดยไม่จำเป็น | Release + backoff ผ่าน visibility | Retry อัตโนมัติ || F9 | 2 rendition สุดท้ายเสร็จพร้อมกัน | ไม่มีใคร publish / publish 2 ครั้ง | Counter `UPDATE ... RETURNING` ภายใต้ row lock | Publish ครั้งเดียว || F10 | สร้าง job แล้วส่งเข้าคิวไม่สำเร็จ | Job ค้าง QUEUED | Transactional outbox + reconciler | Job ถูกส่งเข้าคิวแน่นอน || F11 | Upload หลุดที่ 1.5GB | ต้องเริ่มใหม่ / มีขยะค้าง | Multipart resume + `AbortIncompleteMultipartUpload` 1 วัน | อัปต่อเฉพาะ part ที่ขาด || F12 | ไฟล์เกิน 2GB / ไม่ใช่วิดีโอ | เสีย CPU กับ input ผิด | HeadObject ตรวจขนาดจริง + ffprobe ก่อน fan-out | Reject ก่อน transcode || F13 | Redis ล่ม | Progress หาย | Worker log แล้วทำต่อ, UI poll `GET /videos/{id}` | Job ไม่กระทบ || F14 | PostgreSQL primary ล่ม | Claim/commit ไม่ได้ | Worker ไม่ ack → message กลับเข้าคิว, failover ไป standby | งานช้าลง ไม่หาย || F15 | Upload พุ่ง 10 เท่า | Worker ไม่พอ / ค่าใช้จ่ายพุ่ง | คิวดูดซับ + autoscale ถึงเพดาน + quota ต่อ user | รอนานขึ้น ไม่ล่ม | ### 11.2 Sequence: Worker ตายกลาง transcode ```mermaidsequenceDiagram    autonumber    participant Q as SQS transcode-jobs    participant A as Worker A    participant B as Worker B    participant DB as PostgreSQL    participant S3 as S3     Q->>A: receive job 720p, visibility 3m    A->>DB: claim → RUNNING attempt 1, lease 3m    loop ทุก 1 นาที ขณะ ffmpeg มี progress        A->>DB: extend lease WHERE attempt = 1        A->>Q: ChangeMessageVisibility 3m    end    Note over A: OOM kill / spot reclaim ที่ 60%    Note over Q,DB: ไม่มี heartbeat → lease และ visibility หมดภายใน 3 นาที    Q->>B: redeliver, ApproximateReceiveCount = 2    B->>DB: claim WHERE lease_until < now() → attempt 2    B->>S3: PUT renditions/v9/720p/a2/    B->>DB: DONE WHERE attempt = 2 → 1 row    B->>Q: DeleteMessage``` ### 11.3 Sequence: Zombie worker ```mermaidsequenceDiagram    participant A as Worker A attempt 1    participant B as Worker B attempt 2    participant DB as PostgreSQL    participant S3 as S3     Note over A: network partition 6 นาที ต่อ lease ไม่ได้    B->>DB: claim เพราะ lease ของ A หมด → attempt 2    B->>S3: PUT .../720p/a2/    B->>DB: UPDATE DONE WHERE attempt = 2 → 1 row    A->>S3: PUT .../720p/a1/ ไม่ทับ a2    A->>DB: UPDATE DONE WHERE attempt = 1 → 0 row    Note over A: lost lease → ทิ้งผล a1 ให้ GC ลบ``` --- ## 12. Scaling & Observability ### Scaling- **Upload:** S3 รับ throughput ได้เอง API รับแค่ request เล็กๆ (create/complete)- **Worker:** KEDA `aws-sqs-queue` scaler เป้าหมาย 1 message ต่อ pod (นับ in-flight ด้วย) min 20 / max 800  ส่วนที่เกินเพดาน คิวรับไว้ แล้วแสดง "อยู่ในคิว" ให้ผู้ใช้เห็น- **Scale-in / spot:** SIGTERM → kill ffmpeg → release (`status = QUEUED`, `ChangeMessageVisibility = 0`) worker อื่นทำต่อได้ทันที- **Fairness:** จำกัดงาน in-flight ต่อ user/tenant และแยกคิว priority (เช่นวิดีโอสั้น, 360p ก่อน)- **Instance:** 1 pod = 1 job, scratch บน local NVMe (source 2GB + output) ตั้ง CPU request เต็มเครื่องเพื่อไม่ให้ ffmpeg แย่ง CPU กัน- **Storage:** lifecycle ย้าย source ไป storage class ที่ถูกกว่าหลัง READY 30 วัน และ GC ลบ prefix ของ attempt ที่แพ้ ### Progress- ffmpeg `-progress pipe:1` → `out_time_us / duration` → throttle ทุก 2 วินาที- Worker: `HSET video:{id}:progress {rendition} {pct}` + `PUBLISH` ช่องเดียวกัน- API SSE: **subscribe ก่อน** แล้วส่ง snapshot จาก `HGETALL` จึงไม่มีช่องว่างที่ event หลุด และ ping ทุก 15 วินาทีกัน proxy ตัด connection- Status สุดท้าย (READY/FAILED) มาจาก outbox event → publish เข้าช่องเดียวกัน ### Observability | Metric / Alert | ทำไม ||---|---|| `ApproximateAgeOfOldestMessage` ของ transcode-jobs | คิวระบายทันไหม ใช้ปรับเพดาน worker || `dlq_depth` > 0 | มี poison หรือ bug → on-call ดู `last_error` || `job_attempts` p99 | ถ้าสูง แปลว่า worker ตายบ่อย / heartbeat มีปัญหา || `lost_lease_total` | Zombie เกิดบ่อยแค่ไหน (network / GC) || `upload_to_ready_seconds` p95 | เทียบกับ SLA 45 นาที || Stuck-job query (ข้างล่าง) ทุก 5 นาที | พิสูจน์ว่าไม่มีงานหาย | ```sql-- ต้องได้ 0 row: job ที่ไม่มีใครทำ (ถ้าเจอ reconciler enqueue ใหม่ได้ทันที เพราะ claim idempotent)SELECT id, video_id, rendition, status, attemptFROM transcode_jobsWHERE (status = 'QUEUED'  AND updated_at  < now() - interval '2 hours')   OR (status = 'RUNNING' AND lease_until < now() - interval '15 minutes');``` --- ## 13. Trade-offs & Alternatives | การตัดสินใจ | สิ่งที่เลือก | ทางเลือกอื่น | เหตุผล / สิ่งที่ยอมเสีย ||---|---|---|---|| Upload | Presigned multipart ตรงเข้า S3 | Stream ผ่าน API | API ไม่ต้องรับ 1.4 Gbps และ resume ได้ แต่ต้องตรวจขนาดจริงเอง || งานต่อหน่วย | 1 job ต่อ rendition | 1 job ต่อวิดีโอ (ffmpeg multi-output) | ขนานได้ 4 เท่าและ retry แยกกัน แต่ decode source ซ้ำ 4 รอบ || Delivery semantics | At-least-once + idempotent commit | Exactly-once | Exactly-once ทำไม่ได้จริงเมื่อ worker ตายได้ จึงยอมทำซ้ำบางครั้ง (เสีย CPU) แต่ผลไม่เสีย || ตรวจ worker ตาย | Lease 3 นาที + heartbeat | Visibility timeout ยาวตายตัว | ตรวจพบเร็วและไม่ทำซ้ำพร้อมกัน แต่ต้องเขียน heartbeat เอง || สถานะงาน | PostgreSQL + SQS (แนวทาง A) | Temporal / Step Functions (B) | Component น้อยและทีมคุ้นเคย แต่ต้องเขียน fan-in/retry เอง ถ้ามีขั้นเพิ่ม (moderation, DRM) จะย้ายไป B || ขนาด task | ทั้ง rendition | Chunked parallel (C) | ง่ายกว่ามาก แต่ worker ตายเสียงานสูงสุด ~30 นาที ถ้า SLA ต้องดูได้ภายในไม่กี่นาที หรือวิดีโอยาวเป็นชั่วโมง จะใช้ C || Progress | Redis pub/sub + SSE | WebSocket, polling DB | SSE ทางเดียวพอและ reconnect เองได้ ส่วน Redis ไม่ใช่ source of truth || Compute | Spot + autoscale มีเพดาน | On-demand เผื่อ peak | ถูกกว่ามาก แต่ถูกเรียกคืนได้ (รับได้เพราะงาน retry ได้) และ peak ต้องรอคิว | **ถ้ามีเวลามากกว่านี้:** checkpoint ระดับ HLS segment (resume จาก segment ล่าสุดแทนเริ่มใหม่), per-title encoding ladder,publish แบบ progressive (ให้ดู 360p ก่อน), content moderation ก่อน publish, DRM และ multi-region --- ## References - Amazon SQS Visibility Timeout: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html- Amazon SQS Dead-letter Queues: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html- Amazon S3 Multipart Upload: https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html- FFmpeg Formats (HLS muxer): https://ffmpeg.org/ffmpeg-formats.html- Temporal Documentation: https://docs.temporal.io/

10Notes: อธิบายเพิ่มเติม

รายละเอียดเชิงลึกที่ไม่จำเป็นต้องเขียนทั้งหมดในไฟล์ แต่ผู้ตรวจมักถามต่อ ถ้าตอบได้จะแสดงว่าเข้าใจกลไกจริง ไม่ได้แค่จำ pattern

N1 · Visibility timeout vs heartbeat vs lease

Visibility timeout ตัวเดียวต้องเลือกระหว่าง "ตรวจพบ worker ตายช้า" (ตั้งยาว) หรือ "งานถูกทำซ้ำพร้อมกัน" (ตั้งสั้น) heartbeat ช่วยให้ได้ทั้งสองอย่าง: timeout สั้นแต่ต่อได้เรื่อยๆ ส่วน lease ใน DB มีไว้เพราะ SQS ไม่ได้บอกเราว่าใครเป็นเจ้าของงาน และ standard queue ยังส่ง message ซ้ำได้ (at-least-once) attempt ใน DB จึงเป็นตัวตัดสินสุดท้าย ส่วน FIFO queue ช่วยเรื่อง dedupe ตอน send ภายใน 5 นาทีเท่านั้น ไม่ได้ช่วยเคส worker ตาย จึงไม่จำเป็นสำหรับโจทย์นี้

visibility-timeline.txt
ตัวเลือก 1: visibility timeout ยาวตายตัว 45 นาที ไม่มี heartbeat
  t=0:00  receive
  t=1:00  worker ตาย
  t=45:00 message กลับมา          → เสียเวลา 44 นาทีโดยไม่มีใครทำงาน

ตัวเลือก 2: visibility timeout สั้น 5 นาที ไม่มี heartbeat
  t=0:00  A receive (งานยาว 20 นาที)
  t=5:00  message กลับมาทั้งที่ A ยังทำอยู่ → B ทำซ้ำ, t=10:00 C ทำซ้ำ ...
          → CPU ×4 และ output ชนกัน ถ้าไม่มี fencing

ตัวเลือก 3 (เลือก): lease สั้น 3 นาที + heartbeat ทุก 1 นาทีตาม progress จริง
  t=0:00  A receive, claim attempt 1
  t=1:00  heartbeat → visible อีกครั้งที่ 4:00, lease_until 4:00
  t=2:00  heartbeat → 5:00
  t=2:10  A ตาย
  t=5:00  message กลับมา → B claim attempt 2   → เสียเวลาว่างไม่เกิน 3 นาที

ข้อจำกัด SQS: visibility timeout รวมต่อครั้งที่ receive ต่อได้ไม่เกิน 12 ชั่วโมง
            งาน 30 นาทีจึงไม่ติดเพดาน แต่งาน 4K ยาว 3 ชั่วโมงควรตัด chunk (แนวทาง C)

N2 · Spot instance และ scale-in กลางงาน

งาน transcode retry ได้และไม่ผูกกับเครื่อง จึงเหมาะกับ spot ซึ่ง AWS แจ้งล่วงหน้าประมาณ 2 นาทีก่อนเรียกคืน สิ่งที่ต้องทำคือ release งานทันที (ChangeMessageVisibility เป็น 0) แทนการปล่อยให้ lease หมดเอง ส่วน autoscaler ตอน scale-in ก็ฆ่า pod ที่กำลังทำงานอยู่ได้ ถ้างานยาวจนเสียดาย ให้ใช้ KEDA ScaledJob (1 message ต่อ 1 Kubernetes Job ซึ่งจบเองเมื่อทำเสร็จ) แทน ScaledObject หรือทำ chunk ให้เล็กลง (แนวทาง C) ข้อควรระวังคือ การ release ก็นับเป็น receive ด้วย maxReceiveCount จึงต้องเผื่อให้พอกับจำนวน spot interruption ที่คาดไว้

main.go
func main() {
	// SIGTERM มาจาก: k8s scale-in, rolling deploy, node drain เมื่อได้ spot interruption notice (~2 นาที)
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()

	w := mustNewWorker()
	// ctx ถูก cancel → exec.CommandContext kill ffmpeg → handle() เห็น ctx.Err()
	// → release: job กลับเป็น QUEUED + ChangeMessageVisibility(0)
	// → worker อื่นหยิบได้ทันที ไม่ต้องรอ lease หมด 3 นาที
	if err := w.Run(ctx); err != nil {
		slog.Error("worker stopped", "err", err)
		os.Exit(1)
	}
}

// Pod spec: terminationGracePeriodSeconds: 60 (พอสำหรับ release + ลบ scratch dir)
// ไม่ตั้ง 30 นาทีเพื่อรองานจบ เพราะ spot ให้เวลาแค่ ~2 นาทีอยู่ดี

N3 · HLS/DASH และ ABR ladder

ผลลัพธ์ที่ถูกต้องไม่ใช่ไฟล์ MP4 4 ไฟล์ แต่คือ adaptive bitrate: แต่ละ rendition ถูกตัดเป็น segment ~4 วินาที พร้อม media playlist และมี master playlist ที่บอก player ว่ามี rendition อะไรบ้าง player จะสลับความละเอียดตาม bandwidth ได้ที่รอยต่อ segment ก็ต่อเมื่อ keyframe ตรงกันทุก rendition (ใช้ -force_key_frames ทุก 2 วินาที + -sc_threshold 0) ถ้าอยากใช้ไฟล์ชุดเดียวทั้ง HLS และ DASH ให้ใช้ fMP4/CMAF segment แทน .ts

master.m3u8
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-STREAM-INF:BANDWIDTH=5500000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"
1080p/a1/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3100000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
720p/a2/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1650000,RESOLUTION=854x480,CODECS="avc1.64001e,mp4a.40.2"
480p/a1/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=640x360,CODECS="avc1.64001e,mp4a.40.2"
360p/a1/index.m3u8

N4 · ต้นทุน: compute, storage, egress

  • Compute เป็นต้นทุนหลัก (~500,000 worker-minutes/วัน) ลดได้ด้วย spot, ไม่ upscale (source 720p ทำแค่ 3 rendition), ladder ที่ปรับตามเนื้อหา (per-title) และใช้ GPU encoder กับ rendition ต่ำ (เร็วกว่ามาก แต่คุณภาพต่อ bitrate ต่ำกว่า x264)
  • Storage ~375TB/เดือน ย้าย source ไป storage class ที่ถูกกว่าหลัง READY 30 วัน ลบ prefix ของ attempt ที่แพ้ และ abort multipart ที่ค้าง
  • Egress เสิร์ฟผ่าน CDN เสมอ segment ที่ immutable (path มี attempt) จึง cache ได้ยาว ส่วน master playlist ใช้ TTL สั้น
  • เพดาน worker คือปุ่มแลกระหว่างเงินกับ latency ตอน peak ควรตั้งจาก SLA ที่ตกลงกันไว้ ไม่ใช่ตั้งไว้เผื่อไม่จำกัด

N5 · พิสูจน์ว่างานไม่หายและไม่ค้าง

ต้องวัดให้เห็นจริง ไม่ใช่แค่เชื่อ design metric หลักคือ ApproximateAgeOfOldestMessage (คิวระบายทันไหม), dlq_depth (ควรเป็น 0), job_attempts_p99 (ถ้าสูงแปลว่า worker ตายบ่อยหรือ heartbeat มีปัญหา), lost_lease_total และ upload_to_ready_seconds_p95 เทียบกับ SLA ถ้าจะทดสอบ ให้ใช้ chaos test: kill -9 worker สุ่มระหว่าง transcode แล้วตรวจว่าทุก video จบที่ READY หรือ FAILED และ query ข้างล่างได้ 0 row

invariant-check.sql
-- 1) งานไม่หาย: ไม่มี job ที่ค้างโดยไม่มีใครทำ (ต้องได้ 0 row → alert ทุก 5 นาที)
SELECT id, video_id, rendition, status, attempt, updated_at
FROM transcode_jobs
WHERE (status = 'QUEUED'  AND updated_at  < now() - interval '2 hours')
   OR (status = 'RUNNING' AND lease_until < now() - interval '15 minutes');
-- เจอแล้ว reconciler re-enqueue ได้เลย เพราะ claim idempotent (message ซ้ำไม่เป็นไร)

-- 2) fan-in ถูกต้อง: counter ต้องตรงกับจำนวน DONE จริง
SELECT v.id, v.renditions_done, count(j.*) FILTER (WHERE j.status = 'DONE') AS actual
FROM videos v JOIN transcode_jobs j ON j.video_id = v.id
GROUP BY v.id, v.renditions_done
HAVING v.renditions_done <> count(j.*) FILTER (WHERE j.status = 'DONE');

-- 3) READY ต้องครบทุก rendition
SELECT v.id FROM videos v
WHERE v.status = 'READY'
  AND EXISTS (SELECT 1 FROM transcode_jobs j WHERE j.video_id = v.id AND j.status <> 'DONE');

N6 · คำศัพท์

คำความหมาย
Visibility timeout

ช่วงเวลาที่ message ถูกซ่อนหลังถูก receive ถ้าไม่ลบภายในเวลานี้จะกลับเข้าคิว

Heartbeat

สัญญาณเป็นระยะจาก worker เพื่อต่อ lease/visibility บอกว่ายังทำงานอยู่

Lease

สิทธิ์ทำงานชิ้นหนึ่งแบบมีวันหมดอายุ หมดแล้วคนอื่นเอาไปทำได้

Fencing token

เลขที่เพิ่มขึ้นทุกครั้งที่ได้ lease ใช้ปฏิเสธ write จาก worker ที่ถือ lease เก่า

DLQ

Dead-letter queue: ที่พักของ message ที่ล้มเหลวเกินจำนวนครั้งที่กำหนด

Poison message

Message ที่ทำให้ consumer ล้มเหลวทุกครั้งที่ประมวลผล

Fan-out / fan-in

แตกงานเป็นหลายชิ้นขนานกัน แล้วรวมผลเมื่อครบทุกชิ้น

Rendition / ABR ladder

วิดีโอฉบับความละเอียด/bitrate หนึ่ง และชุดของ rendition ที่ player เลือกสลับได้

HLS / DASH

โปรโตคอล adaptive streaming ที่แบ่งวิดีโอเป็น segment สั้นพร้อม playlist

GOP / keyframe

กลุ่มเฟรมที่เริ่มด้วย keyframe ซึ่ง decode ได้โดยไม่พึ่งเฟรมอื่น

อ่านเอกสารทางการ: Amazon SQS Visibility Timeout ↗
อ่านเอกสารทางการ: Amazon SQS Dead-letter Queues ↗
อ่านเอกสารทางการ: Amazon S3 Multipart Upload ↗
อ่านเอกสารทางการ: FFmpeg Formats (HLS, segment, concat) ↗