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

โจทย์มีคำสำคัญ 4 คำ: 20 instance ใช้ร่วมกัน (ต้องมี state กลางและตัดสินแบบ atomic), แม่นยำพอสมควร (ต้องนิยามเป็นตัวเลขว่ายอมคลาดได้เท่าไร), latency ไม่เกิน 2ms (ได้แค่ 1 round trip และต้องมี timeout) และ ไม่เป็น single point of failure (Redis ล่มแล้ว API ต้องยังทำงาน) คำตอบที่ดีต้องแปลงทั้ง 4 คำเป็นกลไก และตัวเลขที่ตรวจสอบได้

invariant.txt
สำหรับทุก api_key และทุกช่วงเวลา T:
  จำนวน request ที่ถูกปล่อยผ่าน ≤ burst + rate × T
  (เช่น burst 1,000, rate 1,000/นาที → 1 นาทีใดๆ ผ่านได้ไม่เกิน ~2,000
   และเฉลี่ยระยะยาวไม่เกิน 1,000/นาที)

-> ตัดสินที่ Redis ด้วย script เดียวแบบ atomic (ผู้ตัดสินกลางของ 20 gateway)
-> ยอมให้เกินได้ "ชั่วคราวและมีขอบเขต" เฉพาะตอน degraded (Redis ล่ม/failover)
-> ห้ามทำให้ request ปกติช้าลงเกิน 2ms และห้ามทำให้ API ล่มตาม Redis
FUNCTIONAL
  • จำกัด request ต่อ API key ตาม plan และ override รายลูกค้า
  • เกิน limit ตอบ 429 + Retry-After + จำนวนคงเหลือ
  • เปลี่ยน limit ได้โดยไม่ deploy และมีผลภายใน 30 วินาที
  • Request ที่ยังไม่ผ่าน auth จำกัดต่อ IP
NON-FUNCTIONAL
  • Limiter เพิ่ม latency ≤ 2ms ที่ p99
  • ปกติไม่เกิน limit ตอน degraded เกินได้แบบมีขอบเขต (~25%)
  • Redis ล่ม → API ยังให้บริการได้ (fail-open แบบมีเพดาน)
  • Scale แบบ horizontal ทั้ง gateway และ Redis

Capacity: สมมติ 50,000 key ที่ active และ traffic peak 100k RPS (≈ 5k RPS ต่อ gateway) ทุก request คือ 1 EVALSHA จึงเป็น 100k scripts/s ซึ่ง Redis 1 core รับได้ราว 50–100k/s ต้องใช้ Redis Cluster 3 primary เพื่อให้มี headroom ส่วน memory แทบไม่มีผล: bucket ละ ~100 B × 50k ≈ 5 MB ข้อจำกัดจริงคือ CPU ต่อ shard และ RTT RTT ใน AZ เดียวกัน 0.2–0.5ms ทำให้ budget 2ms พอสำหรับ 1 round trip เท่านั้น และถ้า key เดียวยิง 1,000 rps จะเกิด hot key บน shard เดียว ตัวเลขนี้คือเหตุผลของแนวทาง B

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

ทุกแนวทางใช้ แกนร่วม ชุดเดียวกัน (key design, config store, contract 429 และ fail-open แบบมีเพดาน) สิ่งที่ต่างกันคือ ใครตัดสินแต่ละ request และบ่อยแค่ไหนที่ต้องคุยกับ Redis ซึ่งแลกกันระหว่างความแม่นยำ, latency และ memory

เกณฑ์A · Token bucketB · LeasingC · Sliding log
ผู้ตัดสิน

Redis Lua script ทุก request

Redis ตอนยืม quota, gateway ตัดใน memory

Redis Lua + ZSET ทุก request

Redis call ต่อ request

1 RTT (~0.3–0.8ms)

~0 สำหรับ key ใหญ่ (ยืมเป็นก้อน)

1 RTT แต่ script หนักกว่า

ความแม่นยำ

ตรงตาม token bucket (ปกติไม่เกินเลย)

เกินได้ ≤ stock ที่ค้าง และ 429 เกินจริงได้

แม่น 100% ภายใน window

Memory ต่อ key

~100 B (2 field)

~100 B + stock ใน gateway

O(limit): 1,000 entry ≈ 80 KB

ความซับซ้อน

ต่ำ: script เดียว + fallback

กลาง: async refill, chunk size, lease TTL

ต่ำ แต่ต้องคุมขนาด ZSET

เหมาะกับ

API quota ทั่วไป และคำตอบหลักในห้องสอบ

Hot key ที่ rate สูงมาก

Limit ต่ำที่สำคัญ: login, OTP

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

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

ส่วนนี้ต้องมีในทุกแนวทาง เพราะแก้ปัญหาเรื่องการระบุตัวตน การเก็บกฎ การสื่อสารกับ client และการทำงานตอน Redis ล่ม ซึ่งไม่ขึ้นกับว่าใช้ algorithm อะไร

Key & rule: 1 key = 1 bucket

Limiter ทำงานหลัง auth จึงรู้ api_key_id แล้ว ให้ใช้ id นี้เป็นชื่อ key ใน Redis ไม่ใช้ secret ดิบ และครอบด้วย hash tag {…} เพื่อให้กฎหลายตัวของ key เดียวกันอยู่ slot เดียว ในอนาคตจะเช็คหลายกฎใน script เดียวได้

key-design.txt
Redis key ต่อหนึ่งกฎ (1 key = 1 bucket):

  rl:{<api_key_id>}                 ← กฎหลัก 1,000/นาที ต่อ key
  rl:{<api_key_id>}:POST:/v1/orders ← กฎย่อยต่อ route (ถ้ามี)
  rl:ip:{<ip>}                      ← request ที่ยังไม่ผ่าน auth

- ใช้ api_key_id (UUID จากขั้น auth) ไม่ใช้ secret ดิบ: key ใน Redis ถูก log/dump ได้
- {...} คือ hash tag: กฎทุกตัวของ key เดียวกันอยู่ slot เดียว
  → ถ้าวันหนึ่งต้องเช็คหลายกฎใน script เดียว (multi-key) ก็ทำได้ใน Redis Cluster
- value เป็น HASH { tokens, ts } ประมาณ 100 bytes ต่อ bucket

Config store: แยก "กฎ" ออกจาก "สถานะ"

กฎ (plan, override) ต้อง durable จึงอยู่ใน PostgreSQL ส่วนสถานะ bucket หายได้โดยไม่เสียหาย (bucket หาย = เต็ม) จึงอยู่ใน Redis Gateway โหลดกฎทั้งหมดไว้ใน memory เพื่อไม่ให้มี I/O เพิ่มบน hot path และถ้า PostgreSQL ล่มก็ใช้ชุดล่าสุดต่อ (last known good) กฎส่งเข้า script ผ่าน ARGV ทุกครั้ง การเปลี่ยน plan จึงไม่ต้อง migrate bucket

schema.sql
-- Config ของ limit อยู่ใน PostgreSQL (source of truth ของ "กฎ")
-- ส่วน "สถานะ bucket" อยู่ใน Redis (สร้างใหม่ได้ ไม่ต้อง durable)
CREATE TABLE plans (
  id            text PRIMARY KEY,            -- 'free' | 'pro' | 'enterprise'
  limit_per_min int  NOT NULL CHECK (limit_per_min > 0),
  burst         int  NOT NULL CHECK (burst > 0)
);

CREATE TABLE api_keys (
  id         uuid PRIMARY KEY,
  key_hash   bytea NOT NULL UNIQUE,          -- sha256(secret) ไม่เก็บ secret ดิบ
  tenant_id  uuid  NOT NULL,
  plan_id    text  NOT NULL REFERENCES plans (id),
  status     text  NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'REVOKED')),
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- override เฉพาะลูกค้า (เช่น ขอเพิ่มชั่วคราวช่วงแคมเปญ)
CREATE TABLE rate_limit_overrides (
  api_key_id    uuid PRIMARY KEY REFERENCES api_keys (id),
  limit_per_min int  NOT NULL CHECK (limit_per_min > 0),
  burst         int  NOT NULL CHECK (burst > 0),
  expires_at    timestamptz,
  updated_at    timestamptz NOT NULL DEFAULT now()
);
config-cache.go
// Gateway ถือกฎทั้งหมดไว้ใน memory: resolve rule ต้องไม่มี I/O บน hot path
type ConfigCache struct {
	rules atomic.Pointer[map[string]Rule] // api_key_id → rule (copy-on-write)
	def   Rule                            // กฎ default สำหรับ key ที่ยังไม่อยู่ใน cache
}

func (c *ConfigCache) Resolve(keyID string) Rule {
	if m := c.rules.Load(); m != nil {
		if r, ok := (*m)[keyID]; ok {
			return r
		}
	}
	return c.def
}

// Run โหลดกฎใหม่เป็นระยะ ถ้า PostgreSQL ล่มจะใช้ชุดล่าสุดต่อไป (last known good)
func (c *ConfigCache) Run(ctx context.Context, db *pgxpool.Pool, every time.Duration) {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		if m, err := loadRules(ctx, db); err != nil {
			configReloadErrors.Inc() // alert ถ้าล้มติดกันนาน แต่ไม่กระทบ traffic
		} else {
			c.rules.Store(&m)
		}
		select {
		case <-ctx.Done():
			return
		case <-t.C:
		}
	}
}

func loadRules(ctx context.Context, db *pgxpool.Pool) (map[string]Rule, error) {
	rows, err := db.Query(ctx, `
		SELECT k.id::text,
		       COALESCE(o.limit_per_min, p.limit_per_min),
		       COALESCE(o.burst, p.burst)
		FROM api_keys k
		JOIN plans p ON p.id = k.plan_id
		LEFT JOIN rate_limit_overrides o
		       ON o.api_key_id = k.id AND (o.expires_at IS NULL OR o.expires_at > now())
		WHERE k.status = 'ACTIVE'`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	m := make(map[string]Rule, 64_000)
	for rows.Next() {
		var id string
		var limit, burst int
		if err := rows.Scan(&id, &limit, &burst); err != nil {
			return nil, err
		}
		m[id] = Rule{Limit: limit, Window: time.Minute, Burst: burst}
	}
	return m, rows.Err()
}

429 contract และ retry ของ client

Rate limiter ที่ดีต้องบอก client ว่าควรทำอะไรต่อ: ตอบ 429 พร้อม Retry-After และจำนวนคงเหลือ Request ที่ถูกปฏิเสธต้อง ไม่หัก token ไม่อย่างนั้น client ที่ retry ถี่จะถูกล็อกไม่มีวันหลุด และ SDK ต้องทำ backoff + jitter เพื่อไม่ให้ client นับพันยิงกลับพร้อมกัน

middleware.go
// Middleware ใน gateway: limiter เป็น library ใน process ไม่ใช่ service แยก
// (service แยก = เพิ่ม network hop อีก 1 ต่อ และเป็นจุดล่มใหม่)
func RateLimit(l Limiter, cfg *ConfigCache) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			keyID, ok := auth.APIKeyID(r.Context()) // ได้จาก auth middleware ก่อนหน้า
			if !ok {
				next.ServeHTTP(w, r) // request ไม่มี key ใช้กฎต่อ IP แยกอีกชุด
				return
			}
			rule := cfg.Resolve(keyID)
			d := l.Allow(r.Context(), keyID, rule, 1)

			h := w.Header()
			h.Set("X-RateLimit-Limit", strconv.Itoa(rule.Limit))
			h.Set("X-RateLimit-Remaining", strconv.Itoa(max(d.Remaining, 0)))
			if d.Degraded {
				limiterDegraded.Inc() // วัดว่าช่วงไหนตัดสินด้วย local fallback
			}
			if !d.Allowed {
				secs := int(math.Ceil(d.RetryAfter.Seconds()))
				h.Set("Retry-After", strconv.Itoa(max(secs, 1)))
				h.Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusTooManyRequests)
				_, _ = w.Write([]byte(`{"code":"RATE_LIMITED","message":"too many requests"}`))
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}
client-retry.ts
// ฝั่ง client SDK: เคารพ Retry-After และใส่ jitter กัน retry storm
async function callApi(url: string, init: RequestInit, maxAttempts = 4) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(url, init);
    if (res.status !== 429 || attempt === maxAttempts) return res;

    const retryAfter = Number(res.headers.get("Retry-After") ?? "1");
    const base = Math.max(retryAfter, 2 ** (attempt - 1)) * 1_000;
    const jitter = Math.random() * base * 0.3; // client หลายตัวจะไม่ยิงกลับพร้อมกัน
    await new Promise((resolve) => setTimeout(resolve, base + jitter));
  }
}

Fail-open แบบมีเพดาน: timeout + breaker + local fallback

นี่คือคำตอบของคำว่า "ไม่เป็น SPOF" มี 3 ชั้น:

  1. 1
    Deadline 2ms ต่อ call

    Redis ช้าเกิน budget → ตัดสินด้วย local fallback ทันที ห้าม retry

  2. 2
    Circuit breaker

    Error ติดกัน 5 ครั้ง → OPEN 1 วินาที ไม่ยิง Redis เลย จึงไม่เสีย 2ms ทุก request ระหว่างที่ Redis ล่ม

  3. 3
    Local limiter = limit / N

    N คือจำนวน gateway ที่ healthy รวมทั้ง fleet จึงยังประมาณ limit เดิม ไม่ใช่ปล่อยผ่านหมด (fail-open เต็ม) หรือปฏิเสธหมด (fail-closed)

CODEbreaker-state.mmd
stateDiagram-v2
    [*] --> CLOSED
    CLOSED --> OPEN: timeout/error ติดกัน ≥ 5 ครั้ง
    OPEN --> HALF_OPEN: ครบ cooldown 1s
    HALF_OPEN --> CLOSED: probe สำเร็จ
    HALF_OPEN --> OPEN: probe ล้ม
    note right of OPEN
        ไม่ส่ง request ไป Redis เลย
        ตัดสินด้วย local limiter (limit / N)
    end note
RESULT

กำลังวาด diagram…

breaker.go
// Circuit breaker แบบเบา: ไม่มี lock บน hot path
type Breaker struct {
	failures  atomic.Int32
	openUntil atomic.Int64 // unix nano, 0 = CLOSED
	threshold int32         // 5
	cooldown  time.Duration // 1s
}

func (b *Breaker) Ready() bool {
	until := b.openUntil.Load()
	if until == 0 {
		return true // CLOSED
	}
	now := time.Now().UnixNano()
	if now < until {
		return false // OPEN
	}
	// HALF_OPEN: CAS ให้ goroutine เดียวได้เป็น probe ที่เหลือยังใช้ fallback
	return b.openUntil.CompareAndSwap(until, now+int64(b.cooldown))
}

func (b *Breaker) Success() {
	if b.failures.Load() != 0 {
		b.failures.Store(0)
	}
	if b.openUntil.Load() != 0 {
		b.openUntil.Store(0) // probe ผ่าน → CLOSED
	}
}

func (b *Breaker) Failure() {
	if b.failures.Add(1) >= b.threshold {
		b.openUntil.Store(time.Now().Add(b.cooldown).UnixNano())
		b.failures.Store(0)
	}
}
fallback.go
// Local fallback: ใช้ตอน Redis ช้า/ล่ม ให้ API ยังให้บริการได้และยังมีเพดาน
// หาร limit ด้วยจำนวน gateway ที่ healthy → รวมทั้ง fleet ≈ limit เดิม (ถ้า LB กระจายเท่าๆ กัน)
type LocalFallback struct {
	mu        sync.Mutex
	limiters  map[string]*fallbackEntry // production ใช้ LRU จำกัดขนาด
	instances func() int                // จาก service discovery เช่น 20
}

type fallbackEntry struct {
	lim  *rate.Limiter // golang.org/x/time/rate
	rule Rule
	n    int
}

func (f *LocalFallback) Allow(keyID string, rule Rule, cost int) Decision {
	n := max(f.instances(), 1)
	perSec := float64(rule.Limit) / rule.Window.Seconds() / float64(n)

	f.mu.Lock()
	e, ok := f.limiters[keyID]
	if !ok || e.rule != rule || e.n != n {
		e = &fallbackEntry{
			lim:  rate.NewLimiter(rate.Limit(perSec), max(rule.Burst/n, 1)),
			rule: rule,
			n:    n,
		}
		f.limiters[keyID] = e
	}
	f.mu.Unlock()

	if e.lim.AllowN(time.Now(), cost) {
		return Decision{Allowed: true, Remaining: int(e.lim.Tokens()), Degraded: true}
	}
	return Decision{
		Allowed:    false,
		RetryAfter: time.Duration(float64(cost) / perSec * float64(time.Second)),
		Degraded:   true,
	}
}

04แนวทาง A: Redis Token Bucket ด้วย Lua Script

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

เก็บ bucket ต่อ key ใน Redis และคำนวณ refill กับตัด token แบบ atomic ใน script เดียว แม่นยำและเป็นแบบที่นิยมที่สุด

เหมาะเมื่อ

API quota ทั่วไปที่ต้องแม่นข้ามทุก instance, ทีมต้องการกลไกที่อธิบายและทดสอบง่าย และเป็นคำตอบหลักในห้องสอบ

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

มี key เดียวที่ traffic สูงจน shard ที่ถือมัน CPU เต็ม หรือ gateway อยู่คนละ region กับ Redis จน RTT เกิน budget

Architecture

ทุก gateway เรียก Redis Cluster ตัวเดียวกันด้วย EVALSHA กฎอยู่ใน memory ของ gateway ที่โหลดจาก PostgreSQL เป็นระยะ ส่วน Redis เป็นแค่ที่เก็บสถานะ bucket

CODEarchitecture-a.mmd
flowchart LR
    C[Clients<br/>X-API-Key] --> LB[Load Balancer]
    LB --> GW1[Gateway 1<br/>limiter lib + fallback]
    LB --> GW2[Gateway 2..19]
    LB --> GW20[Gateway 20]
    GW1 -- "EVALSHA 1 RTT<br/>timeout 2ms" --> RC[(Redis Cluster<br/>3 primary + 3 replica)]
    GW2 --> RC
    GW20 --> RC
    GW1 --> UP[Upstream services]
    GW2 --> UP
    GW20 --> UP
    PG[(PostgreSQL<br/>plans · api_keys · overrides)] -. "reload ทุก 30s" .-> GW1
    PG -.-> GW2
    PG -.-> GW20
    ADM[Admin API] --> PG
    GW1 -. metrics .-> OBS[Prometheus / Grafana]
RESULT

กำลังวาด diagram…

CODEhappy-path-a.mmd
sequenceDiagram
    autonumber
    participant C as Client
    participant GW as Gateway (1 ใน 20)
    participant CFG as Config cache (in-memory)
    participant R as Redis Cluster
    participant UP as Upstream

    C->>GW: GET /v1/orders (X-API-Key)
    GW->>GW: auth → api_key_id
    GW->>CFG: resolve rule (~µs ไม่มี I/O)
    GW->>R: EVALSHA token_bucket rl:{key_id} [1000, 0.0167, 1]
    R-->>GW: {1, 998, 0} (~0.3–0.8ms)
    GW->>UP: forward
    UP-->>GW: 200
    GW-->>C: 200 + X-RateLimit-Remaining: 998
RESULT

กำลังวาด diagram…

ทำไม GET แล้ว SET และ INCR แล้ว EXPIRE ถึงพัง

naive.go
// ❌ read-modify-write ข้าม network: 2 gateway อ่านค่าเดียวกันแล้วเขียนทับกัน
tokens, _ := rdb.Get(ctx, key).Int()      // G1 และ G2 อ่านได้ 1 พร้อมกัน
if tokens > 0 {
	rdb.Set(ctx, key, tokens-1, 0)         // ทั้งคู่เขียน 0 → ปล่อยผ่าน 2 แต่ตัดไป 1
	return true
}
return false

// ❌ fixed window แบบ INCR แล้วค่อย EXPIRE (2 คำสั่ง ไม่ atomic)
n, _ := rdb.Incr(ctx, "rl:"+keyID+":"+minute).Result()
if n == 1 {
	rdb.Expire(ctx, "rl:"+keyID+":"+minute, time.Minute) // crash ก่อนบรรทัดนี้ = key ไม่มี TTL
}
return n <= 1000 // และยังโดน boundary burst: 1,000 ที่ 00:59 + 1,000 ที่ 01:00

Token bucket ใน Lua script เดียว

Redis รัน script ทีละตัวจนจบ ไม่มี command อื่นแทรกกลาง การ refill, เช็ค และหัก token จึงเป็น atomic โดยไม่ต้องใช้ lock เวลาใช้ redis.call('TIME') ของ Redis ตัวเดียว ไม่ใช้นาฬิกาของ 20 gateway และ request ที่ถูกปฏิเสธไม่หัก token

token_bucket.lua
-- token_bucket.lua
-- KEYS[1] = rl:{<api_key_id>}
-- ARGV[1] = capacity (burst)        เช่น 1000
-- ARGV[2] = refill rate (token/ms)  เช่น 1000/60000 = 0.016666...
-- ARGV[3] = cost ของ request นี้     ปกติ 1
-- return {allowed 0|1, remaining, retry_after_ms}
local capacity = tonumber(ARGV[1])
local rate     = tonumber(ARGV[2])
local cost     = tonumber(ARGV[3])

-- ใช้นาฬิกาของ Redis ตัวเดียว ไม่ใช้เวลาของ gateway 20 เครื่อง (clock skew)
-- Redis 7 replicate script แบบ effects จึงเรียก TIME ก่อน write ได้
local t   = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)

local state  = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1])
local ts     = tonumber(state[2])
if tokens == nil or ts == nil then
  tokens, ts = capacity, now          -- ไม่มี key = bucket เต็ม
end

-- refill ตามเวลาที่ผ่านไป (max 0 กันกรณีเวลาย้อนหลัง failover)
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)

local allowed, retry_after = 0, 0
if tokens >= cost then
  tokens  = tokens - cost
  allowed = 1
else
  retry_after = math.ceil((cost - tokens) / rate)
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
-- bucket ที่ว่างนานพอจะเต็มเอง → ลบทิ้งได้โดยไม่เสียความถูกต้อง
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate) + 1000)
return {allowed, math.floor(tokens), retry_after}
limiter.go
package ratelimit

import (
	"context"
	_ "embed"
	"time"

	"github.com/redis/go-redis/v9"
)

//go:embed token_bucket.lua
var tokenBucketSrc string

// Script.Run ใช้ EVALSHA ก่อน ถ้าเจอ NOSCRIPT (Redis restart/failover) จะ fallback เป็น EVAL เอง
var tokenBucket = redis.NewScript(tokenBucketSrc)

type Rule struct {
	Limit  int           // 1000
	Window time.Duration // 1 นาที
	Burst  int           // capacity ของ bucket ปกติ = Limit
}

type Decision struct {
	Allowed    bool
	Remaining  int
	RetryAfter time.Duration
	Degraded   bool // true = ตัดสินด้วย local fallback
}

type RedisLimiter struct {
	rdb      redis.UniversalClient
	timeout  time.Duration // 2ms = latency budget ทั้งก้อน
	breaker  *Breaker
	fallback *LocalFallback
}

func (l *RedisLimiter) Allow(ctx context.Context, keyID string, rule Rule, cost int) Decision {
	if !l.breaker.Ready() { // OPEN: ไม่เสีย 2ms รอ Redis ที่รู้อยู่แล้วว่าล่ม
		return l.fallback.Allow(keyID, rule, cost)
	}

	ctx, cancel := context.WithTimeout(ctx, l.timeout)
	defer cancel()

	ratePerMs := float64(rule.Limit) / float64(rule.Window.Milliseconds())
	res, err := tokenBucket.Run(ctx, l.rdb, []string{"rl:{" + keyID + "}"},
		rule.Burst, ratePerMs, cost).Int64Slice()
	if err != nil || len(res) != 3 {
		l.breaker.Failure()
		return l.fallback.Allow(keyID, rule, cost) // fail-open แบบมีเพดาน
	}
	l.breaker.Success()
	return Decision{
		Allowed:    res[0] == 1,
		Remaining:  int(res[1]),
		RetryAfter: time.Duration(res[2]) * time.Millisecond,
	}
}

func NewRedisClient(addrs []string) *redis.ClusterClient {
	return redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:                 addrs,
		ContextTimeoutEnabled: true, // ให้ context deadline 2ms มีผลกับ socket จริง
		DialTimeout:           100 * time.Millisecond,
		ReadTimeout:           2 * time.Millisecond,
		WriteTimeout:          2 * time.Millisecond,
		PoolSize:              64,                    // ต่อ node ต่อ gateway
		MinIdleConns:          16,                    // ไม่เสียเวลา dial บน hot path
		PoolTimeout:           2 * time.Millisecond,  // pool เต็ม = ถือว่า fail → fallback
		MaxRetries:            -1,                    // ห้าม retry เกิน budget
	})
}
CODErace-a.mmd
sequenceDiagram
    participant G1 as Gateway 1
    participant G2 as Gateway 2
    participant R as Redis (single-threaded)

    Note over R: rl:{k} tokens = 1
    par request พร้อมกัน
        G1->>R: EVALSHA token_bucket (cost 1)
        G2->>R: EVALSHA token_bucket (cost 1)
    end
    Note over R: script รันทีละตัวจนจบ<br/>ไม่มี command อื่นแทรกกลาง
    R-->>G1: {1, 0, 0} allowed
    R-->>G2: {0, 0, 60} denied
    G1->>G1: forward upstream
    G2->>G2: 429 + Retry-After: 1
RESULT

กำลังวาด diagram…

เมื่อ Redis ล่ม

CODEredis-down.mmd
sequenceDiagram
    autonumber
    participant C as Client
    participant GW as Gateway
    participant BR as Breaker
    participant R as Redis
    participant LF as Local fallback (limit/N)

    C->>GW: request
    GW->>BR: Ready?
    BR-->>GW: CLOSED
    GW->>R: EVALSHA (deadline 2ms)
    R--xGW: timeout
    GW->>BR: Failure() ครบ 5 ครั้ง → OPEN 1s
    GW->>LF: Allow(key, 1000/20 = 50 ต่อนาที)
    LF-->>GW: allowed (degraded)
    GW-->>C: 200 (metric limiter_degraded +1)
    Note over GW,R: ระหว่าง OPEN ไม่ยิง Redis เลย<br/>latency เพิ่ม ≈ 0
    loop ทุก cooldown 1s
        GW->>R: probe 1 request (HALF_OPEN)
        alt สำเร็จ
            GW->>BR: Success() → CLOSED
        else ล้ม
            GW->>BR: คง OPEN อีก 1s
        end
    end
RESULT

กำลังวาด diagram…

ข้อดี
  • แม่นยำตาม token bucket ข้าม 20 gateway
  • Atomic ใน 1 round trip ไม่มี lock ไม่มี retry loop
  • เก็บแค่ 2 ค่าต่อ key และไม่มี boundary burst
  • ไม่มี service ใหม่ limiter เป็นแค่ library
ข้อแลกเปลี่ยน
  • ทุก request ต้องมี 1 RTT ไป Redis
  • Hot key ทำให้ shard เดียวเป็นคอขวด
  • Script block Redis ระหว่างรัน ต้องเขียนให้สั้น

05แนวทาง B: Local Limiter + Quota Leasing จาก Redis

แต่ละ gateway ขอ quota เป็นก้อนจาก Redis มาตัดใน memory ลด round trip ลงมาก แลกกับความแม่นยำที่ลดลงเล็กน้อย

เหมาะเมื่อ

Key ใหญ่ไม่กี่ตัวที่ยิงหลักพัน rps จนเป็น hot key หรือ Redis เริ่มเป็นคอขวดของ CPU ทั้ง cluster

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

Key ส่วนใหญ่มี rate ต่ำ (เช่น 1,000/นาที ≈ 1 rps ต่อ instance) เพราะ chunk จะเหลือ 1 และได้แต่ความซับซ้อนเพิ่ม

Architecture

Gateway ยืม token จาก bucket กลางเป็นก้อน (lease) แล้วตัดใน memory เมื่อ stock ต่ำกว่า low watermark จะเติมแบบ async เพื่อไม่ให้ request ต้องรอ Redis bucket กลางยังใช้ refill แบบเดียวกับ แนวทาง A token ทุกตัวจึงถูกหักจากที่กลางก่อนใช้เสมอ

CODEarchitecture-b.mmd
flowchart LR
    C[Clients] --> LB[Load Balancer]
    LB --> GW1[Gateway 1<br/>local stock ต่อ key]
    LB --> GW2[Gateway 2..20<br/>local stock ต่อ key]
    GW1 -- "lease(want=50)<br/>async เมื่อ stock ต่ำ" --> RC[(Redis Cluster<br/>bucket กลาง)]
    GW2 -- "lease" --> RC
    GW1 --> UP[Upstream]
    GW2 --> UP
    PG[(PostgreSQL config)] -.-> GW1
    PG -.-> GW2
RESULT

กำลังวาด diagram…

lease.lua
-- lease.lua: ยืม token เป็นก้อนจาก bucket กลาง (refill แบบเดียวกับ token_bucket.lua)
-- ARGV[1] = capacity, ARGV[2] = rate (token/ms), ARGV[3] = want
-- return {granted, retry_after_ms}
local capacity = tonumber(ARGV[1])
local rate     = tonumber(ARGV[2])
local want     = tonumber(ARGV[3])

local t   = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)

local state  = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts     = tonumber(state[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)

-- ให้เท่าที่มี (partial grant) ไม่ใช่ all-or-nothing
local granted = math.min(want, math.floor(tokens))
tokens = tokens - granted

redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate) + 1000)

local retry_after = 0
if granted == 0 then
  retry_after = math.ceil((1 - tokens) / rate)
end
return {granted, retry_after}
leasing-limiter.go
var leaseScript = redis.NewScript(leaseSrc)

type leasedBucket struct {
	mu        sync.Mutex
	tokens    int
	expiresAt time.Time // token ที่ยืมมาใช้ได้ไม่เกิน leaseTTL
	inflight  bool      // มี async refill วิ่งอยู่แล้ว
}

type LeasingLimiter struct {
	rdb       redis.UniversalClient
	buckets   sync.Map // keyID → *leasedBucket (production ใช้ LRU)
	leaseTTL  time.Duration
	timeout   time.Duration
	instances func() int
	fallback  *LocalFallback
}

func (l *LeasingLimiter) Allow(ctx context.Context, keyID string, rule Rule) Decision {
	v, _ := l.buckets.LoadOrStore(keyID, &leasedBucket{})
	b := v.(*leasedBucket)
	chunk := l.chunkSize(rule)

	b.mu.Lock()
	if time.Now().After(b.expiresAt) {
		b.tokens = 0 // lease หมดอายุ → ทิ้ง token ค้าง (ยอม under-admit)
	}
	if b.tokens > 0 {
		b.tokens--
		remaining := b.tokens
		if remaining <= chunk/4 && !b.inflight { // low watermark → เติมล่วงหน้า
			b.inflight = true
			go l.refill(keyID, b, rule, chunk)
		}
		b.mu.Unlock()
		return Decision{Allowed: true, Remaining: remaining} // ไม่มี network เลย
	}
	b.mu.Unlock()

	// stock หมด: ยืมแบบ sync 1 RTT (เหมือนแนวทาง A)
	ctx, cancel := context.WithTimeout(ctx, l.timeout)
	defer cancel()
	granted, retry, err := l.lease(ctx, keyID, rule, chunk)
	if err != nil {
		return l.fallback.Allow(keyID, rule, 1)
	}
	if granted == 0 {
		return Decision{Allowed: false, RetryAfter: retry}
	}
	b.mu.Lock()
	l.deposit(b, granted-1) // ใช้เองไป 1 ที่เหลือเก็บเป็น stock
	b.mu.Unlock()
	return Decision{Allowed: true, Remaining: granted - 1}
}

func (l *LeasingLimiter) refill(keyID string, b *leasedBucket, rule Rule, chunk int) {
	// async ไม่อยู่บน hot path ให้เวลามากกว่า 2ms ได้
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	granted, _, err := l.lease(ctx, keyID, rule, chunk)

	b.mu.Lock()
	defer b.mu.Unlock()
	b.inflight = false
	if err == nil && granted > 0 {
		l.deposit(b, granted)
	}
}

// deposit ต้องเรียกขณะถือ b.mu
func (l *LeasingLimiter) deposit(b *leasedBucket, n int) {
	if time.Now().After(b.expiresAt) {
		b.tokens = 0
	}
	b.tokens += n
	b.expiresAt = time.Now().Add(l.leaseTTL)
}

func (l *LeasingLimiter) lease(ctx context.Context, keyID string, rule Rule, want int) (int, time.Duration, error) {
	ratePerMs := float64(rule.Limit) / float64(rule.Window.Milliseconds())
	res, err := leaseScript.Run(ctx, l.rdb, []string{"rl:{" + keyID + "}"},
		rule.Burst, ratePerMs, want).Int64Slice()
	if err != nil {
		return 0, 0, err
	}
	return int(res[0]), time.Duration(res[1]) * time.Millisecond, nil
}

// chunk = rate ที่คาดว่าจะเข้า instance นี้ × leaseTTL แต่ไม่เกิน burst/(4N)
// → stock รวมทั้ง fleet ≤ burst/4 ขอบเขตความคลาดเคลื่อนจึงคำนวณได้
func (l *LeasingLimiter) chunkSize(rule Rule) int {
	n := max(l.instances(), 1)
	perInstancePerSec := float64(rule.Limit) / rule.Window.Seconds() / float64(n)
	c := int(perInstancePerSec * l.leaseTTL.Seconds())
	return min(max(c, 1), max(rule.Burst/(4*n), 1))
}

ความแม่นยำที่เสียไปคำนวณได้

accuracy-b.txt
ความคลาดเคลื่อนของ leasing (N = 20 gateway, stock สูงสุดต่อ instance = S)

1) Over-admit: token ทุกตัวถูกหักจาก bucket กลางก่อนใช้เสมอ
   → ปล่อยผ่านในช่วง T ≤ burst + rate×T + (stock ที่ค้างตอนเริ่มช่วง ≤ N×S)
   → จำกัด S ≤ burst/(4N) ทำให้ส่วนเกินไม่เกิน 25% ของ burst ในช่วงเลวร้ายที่สุด

2) Under-admit (429 ทั้งที่ quota ยังเหลือ): token ไปค้างใน instance ที่ไม่มี traffic
   → เช่น G1 ถือ 40 token แต่ LB ส่ง request ของ key นี้ไป G2 ที่ stock หมด
   → ลดด้วย leaseTTL สั้น (1s) และ chunk ตาม rate จริง

3) ตัวอย่าง: key 60,000/นาที = 1,000 rps, 20 gateway → 50 rps ต่อ instance
   chunk = 50 × 1s = 50 → Redis call ของ key นี้ลดจาก 1,000/s เหลือ ~20/s (-98%)
   key 1,000/นาที = ~0.8 rps ต่อ instance → chunk = 1 = ไม่ได้ประโยชน์ ใช้แนวทาง A แทน
ข้อดี
  • Request ส่วนใหญ่ตัดสินใน memory latency ≈ 0
  • Redis call ของ key ใหญ่ลด ~98%
  • Redis ล่มสั้นๆ ยังใช้ stock ที่มีได้
  • ขอบเขตความคลาดเคลื่อนคำนวณได้จาก chunk size
ข้อแลกเปลี่ยน
  • Token ค้างใน instance ที่ไม่มี traffic ทำให้ 429 ทั้งที่ quota ยังเหลือ
  • Over-admit ได้เท่ากับ stock ที่ค้างอยู่
  • มี state ใน gateway ต้องจัดการ async refill และ LRU

06แนวทาง C: Sliding Window Log ด้วย Sorted Set

เก็บ timestamp ทุก request ใน ZSET นับได้แม่นยำ 100% เหมาะกับ limit ต่ำแต่สำคัญ เช่น login หรือ OTP

เหมาะเมื่อ

Limit ต่ำแต่ผลกระทบสูง เช่น OTP 3 ครั้ง/10 นาที, login ผิด 5 ครั้ง/15 นาที ที่ต้องแม่น 100% และต้องบอกเวลารอได้แม่นยำ

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

Limit สูง (หลักพันต่อนาที) และมี key จำนวนมาก เพราะ memory เป็น O(limit) ต่อ key และ ZREMRANGEBYSCORE ต้องลบทีละมาก

Architecture

ใช้แยกเฉพาะ endpoint ที่ต้องการ เช่น Auth Service เรียก sliding log ทั้งต่อ account และต่อ IP ส่วน API quota ทั่วไปยังเป็นแนวทาง A

CODEarchitecture-c.mmd
flowchart LR
    U[User] --> GW[Gateway]
    GW --> AUTH[Auth Service<br/>/login · /otp]
    AUTH -- "EVALSHA sliding_log<br/>sl:{login:account}<br/>sl:{login:ip}" --> RC[(Redis<br/>ZSET ต่อ subject)]
    AUTH --> PG[(PostgreSQL users)]
    AUTH --> SMS[[SMS / OTP provider]]
    GW -- "API quota ทั่วไป<br/>(แนวทาง A)" --> RB[(Redis token bucket)]
RESULT

กำลังวาด diagram…

sliding_log.lua
-- sliding_log.lua
-- KEYS[1] = sl:{<scope>:<subject>}   เช่น sl:{otp:+66812345678}
-- ARGV[1] = window_ms, ARGV[2] = limit, ARGV[3] = member ที่ unique ต่อ request
-- return {allowed, remaining, retry_after_ms}
local window = tonumber(ARGV[1])
local limit  = tonumber(ARGV[2])

local t   = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)

-- ตัด request ที่หลุด window ออก: หน้าต่างคือ (now - window, now]
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - window)
local count = redis.call('ZCARD', KEYS[1])

if count < limit then
  redis.call('ZADD', KEYS[1], now, ARGV[3])
  redis.call('PEXPIRE', KEYS[1], window)
  return {1, limit - count - 1, 0}
end

-- เต็ม: รอจนตัวที่เก่าที่สุดหลุด window
local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
return {0, 0, tonumber(oldest[2]) + window - now}
sliding-log.go
var slidingLog = redis.NewScript(slidingLogSrc)

type SlidingLogLimiter struct {
	rdb        redis.UniversalClient
	instanceID string        // เช่น hostname ของ pod
	seq        atomic.Uint64 // ทำ member ให้ unique แม้ 2 request มาใน ms เดียวกัน
}

// ใช้กับ limit ต่ำแต่ต้องแม่น เช่น OTP 3 ครั้ง/10 นาที ต่อเบอร์
func (l *SlidingLogLimiter) Allow(ctx context.Context, scope, subject string,
	limit int, window time.Duration) (Decision, error) {

	key := "sl:{" + scope + ":" + subject + "}"
	member := l.instanceID + ":" + strconv.FormatUint(l.seq.Add(1), 10)
	res, err := slidingLog.Run(ctx, l.rdb, []string{key},
		window.Milliseconds(), limit, member).Int64Slice()
	if err != nil {
		return Decision{}, err // caller เลือกเองว่า fail-open หรือ fail-closed
	}
	return Decision{
		Allowed:    res[0] == 1,
		Remaining:  int(res[1]),
		RetryAfter: time.Duration(res[2]) * time.Millisecond,
	}, nil
}

// OTP: ส่ง SMS มีต้นทุนเงินจริงและเสี่ยง abuse → ถ้า Redis ล่มให้ใช้ local limit แบบเข้ม
func (s *OTPService) Send(ctx context.Context, phone string) error {
	d, err := s.limiter.Allow(ctx, "otp", phone, 3, 10*time.Minute)
	if err != nil {
		if !s.strictLocal.Allow(phone) { // เช่น 1 ครั้ง/10 นาที ต่อ instance
			return ErrTooManyRequests
		}
	} else if !d.Allowed {
		return &RetryAfterError{After: d.RetryAfter}
	}
	return s.sms.Send(ctx, phone, s.newCode())
}
CODEsequence-c.mmd
sequenceDiagram
    participant U as User
    participant A as Auth Service
    participant R as Redis ZSET sl:{otp:phone}

    U->>A: POST /otp (ครั้งที่ 3 ใน 10 นาที)
    A->>R: EVALSHA sliding_log [600000, 3, member]
    Note over R: ZREMRANGEBYSCORE ลบของเก่า<br/>ZCARD = 2 ยังไม่ถึง 3 → ZADD
    R-->>A: {1, 0, 0}
    A-->>U: 200 ส่ง OTP แล้ว
    U->>A: POST /otp (ครั้งที่ 4)
    A->>R: EVALSHA sliding_log
    Note over R: ZCARD = 3 → ไม่ ZADD<br/>คืนเวลาที่ตัวเก่าสุดจะหลุด
    R-->>A: {0, 0, 412000}
    A-->>U: 429 Retry-After: 412
RESULT

กำลังวาด diagram…

ทำไมไม่ใช้กับ API quota ทั่วไป

memory-c.txt
Memory ของ sliding log = O(limit) ต่อ subject

  ZSET 1 entry ≈ member 20–30 B + score 8 B + overhead skiplist ≈ 60–100 B

  OTP 3 ครั้ง/10 นาที     × 1M เบอร์     ≈ 3M entry    ≈ 0.3 GB   → รับได้
  API 1,000 ครั้ง/นาที    × 50k api key  ≈ 50M entry   ≈ 4–5 GB   → เปลือง
  (token bucket 50k key × ~100 B ≈ 5 MB)

  CPU: ZREMRANGEBYSCORE เป็น O(log N + M) และ key ที่ limit สูงลบทีละมาก
  → ใช้ C เฉพาะ limit ต่ำที่ต้องแม่น 100% เท่านั้น
ข้อดี
  • แม่น 100% ใน window ใดๆ ไม่มี burst
  • Retry-After แม่นยำจาก timestamp ของตัวเก่าสุด
  • ตรวจสอบย้อนหลังได้ว่า request เกิดตอนไหน
ข้อแลกเปลี่ยน
  • Memory O(limit) ต่อ subject
  • Script หนักกว่า token bucket
  • ต้องทำ member ให้ unique ไม่งั้น request ใน ms เดียวกันทับกัน

07Failure handling

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

สถานการณ์กลไกผลลัพธ์
2 gateway หัก token พร้อมกัน

Lua script รันแบบ atomic ใน Redis

ผ่านตาม limit พอดี

Redis ช้า p99 พุ่ง

Deadline 2ms + MaxRetries ปิด → local fallback

Latency ไม่เกิน budget

Redis ล่มทั้ง cluster

Breaker OPEN + local limiter limit/N

API ทำงานต่อ limit รวม ≈ เดิม

Shard failover (async replication)

ยอมรับ + clamp elapsed ด้วย max(0, …)

Over-admit ≤ 1 burst ต่อ key

Partition: 5/20 gateway หลุดจาก Redis

5 ตัวใช้ fallback 50/นาที

รวมสูงสุด ~1,250/นาที + alert

Clock skew ระหว่าง gateway

redis.call('TIME') ใน script

ไม่ขึ้นกับนาฬิกา gateway

NOSCRIPT หลัง Redis restart

Script.Run fallback เป็น EVAL

เสีย 1 RTT ครั้งเดียว

Bucket ถูก evict

TTL ทุก key + volatile-ttl + alert evicted_keys

ไม่ควรเกิด ถ้าเกิดเกิน ≤ 1 burst

Hot key บน shard เดียว

Quota leasing (B) + negative cache

Redis call ของ key นั้นลด ~98%

PostgreSQL (config) ล่ม

Last known good ใน memory

Traffic ปกติ แก้ limit ไม่ได้ชั่วคราว

Client retry storm หลัง 429

Retry-After + ไม่หัก token + negative cache

Load ของการปฏิเสธต่ำ

Gateway crash ถือ stock อยู่ (B)

Lease TTL 1s + stock ≤ burst/(4N)

Under-admit ชั่วคราว ไม่เกิน limit

ZSET โตเกินเพราะ limit สูง (C)

ใช้ C เฉพาะ limit ต่ำ + PEXPIRE = window

Memory คุมได้

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

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

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

สังเกตโครงสร้าง
  • คำว่า "แม่นยำพอสมควร" ถูกแปลงเป็นตัวเลขตั้งแต่หัวข้อ 1 แล้วทุก failure อ้างกลับมาที่ตัวเลขนั้น
  • Latency budget 2ms ถูกแตกเป็น RTT + script + timeout
  • Fail-open มีทั้ง sequence, state diagram และ code ไม่ใช่แค่ประโยค
ในห้องสอบ 60 นาที
  • ไม่ต้องยาวเท่านี้ ให้ความสำคัญกับหัวข้อ 1, 2, 3, 9, 11 และ 13
  • Code เขียนแค่ Lua script กับ logic fallback ก็พอ
  • ห้ามตัด failure matrix และ sequence ตอน Redis ล่มออก
system-design.md621 บรรทัด · 15 หัวข้อ · 7 Mermaid · 9 code block · 8 ตาราง
# System Design: Distributed Rate Limiter > **โจทย์:** ออกแบบระบบจำกัด request ต่อ API key (เช่น 1,000 ครั้งต่อนาที) ที่ API gateway 20 instance ใช้ร่วมกัน> ต้องแม่นยำพอสมควร latency เพิ่มไม่เกิน 2ms และต้องไม่กลายเป็น single point of failure ## สรุป (TL;DR) - **Algorithm:** token bucket ต่อ API key (capacity = 1,000, refill 1,000/นาที) ไม่มีปัญหา boundary burst แบบ fixed window และเก็บแค่ 2 ค่าต่อ key- **Atomicity:** refill + check + decrement อยู่ใน **Lua script เดียว** บน Redis Cluster (1 round trip, ไม่มี race ระหว่าง 20 gateway) ใช้เวลาจาก `redis.call('TIME')` ไม่ใช้นาฬิกาของ gateway- **Latency ≤ 2ms:** limiter เป็น library ใน gateway (ไม่มี hop เพิ่ม), กฎอยู่ใน memory, Redis อยู่ AZ/region เดียวกัน, deadline 2ms ต่อ call และไม่ retry- **ไม่เป็น SPOF:** Redis ช้า/ล่ม → circuit breaker + **fail-open แบบมีเพดาน** (local limiter `limit / N` ต่อ instance) API ยังให้บริการได้ และ limit รวมยังประมาณเดิม- **ความแม่นยำ:** ปกติแม่นตาม token bucket ทุกประการ ตอน degraded ยอมคลาดได้แบบมีขอบเขตที่คำนวณได้ และวัดได้จาก metric- **Scale ต่อ:** key ที่ traffic สูงมาก (hot key) ใช้ quota leasing (ยืม token เป็นก้อน) ส่วน limit ต่ำที่ต้องแม่น 100% (OTP/login) ใช้ sliding window log --- ## 1. Requirements & Core Invariant ### Functional- จำกัดจำนวน request ต่อ API key ตาม plan (เช่น free 1,000/นาที, enterprise 60,000/นาที) และ override รายลูกค้าได้- เมื่อเกิน limit ตอบ `429 Too Many Requests` พร้อม `Retry-After` และบอกจำนวนคงเหลือใน header- เปลี่ยน limit ของลูกค้าได้โดยไม่ต้อง deploy และมีผลภายใน 30 วินาที- Request ที่ยังไม่ผ่าน auth ถูกจำกัดต่อ IP แยกอีกชุด ### Non-functional- **Latency:** limiter เพิ่ม latency ไม่เกิน **2ms ที่ p99**- **Accuracy:** "แม่นยำพอสมควร" = ปกติไม่เกิน limit เลย ตอน degraded เกินได้ไม่เกิน ~25% และต้องเป็นช่วงสั้น- **Availability:** Redis ล่ม → API ยังให้บริการได้ (limiter ต้อง fail-open) และ limiter ต้องไม่เป็น single point of failure- **Scale:** gateway 20 instance ขึ้นไป, 100k RPS รวม และเพิ่มได้แบบ horizontal- **Observability:** เห็นอัตรา 429 ต่อ plan, latency ของ limiter และช่วงที่ทำงานแบบ degraded ### Core Invariant ```textสำหรับทุก api_key และทุกช่วงเวลา T:  จำนวน request ที่ถูกปล่อยผ่าน ≤ burst + rate × T  (burst = 1,000, rate = 1,000/นาที → เฉลี่ยระยะยาวไม่เกิน 1,000/นาที) ตอนปกติ: บังคับที่ Redis ด้วย Lua script แบบ atomic (ผู้ตัดสินกลางของทุก gateway)ตอน degraded: ยอมคลาดได้แบบมีขอบเขตที่คำนวณได้ แต่ห้ามทำให้ API ล่มหรือช้าเกิน 2ms``` > Rate limiter เป็นการป้องกันระดับ **best-effort ที่มีขอบเขต** ไม่ใช่ข้อมูลเงิน> จึงเลือก **availability + latency มากกว่า strict consistency** ตั้งแต่ต้น --- ## 2. Assumptions & Capacity Estimation | Assumption | ค่า ||---|---|| Gateway | 20 instance, stateless, อยู่หลัง load balancer (round-robin) || API key ที่ active | 50,000 key (รวมทั้งหมด 500,000 key) || Traffic peak | 100,000 RPS รวม (≈ 5,000 RPS ต่อ gateway) || Limit default | 1,000/นาที ต่อ key, burst = 1,000 || Redis | Redis 7 Cluster ใน region/AZ เดียวกับ gateway, RTT 0.2–0.5ms || Config store | PostgreSQL (มีอยู่แล้วสำหรับ API key management) | **ประมาณการ:**- **Redis ops:** ทุก request = 1 `EVALSHA` → **100k scripts/s** script สั้นแบบนี้ Redis 1 core รับได้ราว 50–100k/s  → ใช้ **Redis Cluster 3 primary** (+3 replica) ได้ headroom ~2–3 เท่า และเพิ่ม shard ได้เมื่อโต- **Memory:** bucket 1 ตัว (HASH `tokens`, `ts` + key) ≈ 100–150 B × 50k key ≈ **7.5 MB** ต่อให้ทุก key active (500k) ก็แค่ ~75 MB  → memory ไม่ใช่ปัญหา ข้อจำกัดคือ **CPU และ latency**- **Latency budget 2ms:** RTT 0.2–0.5ms + script 10–30µs + queueing ใน Redis → p99 ~1ms ถ้า CPU ของ shard < 60%  → ตั้ง **deadline 2ms** ต่อ call ถ้าเกินก็ตัดสินด้วย local fallback แทน- **Hot key:** limit 1,000/นาที = 16.7 rps ต่อ key ถือว่าเบามาก แต่ enterprise key 60,000/นาที = 1,000 rps อยู่บน shard เดียว  → ต้องมีแผนสำหรับ hot key (ดูหัวข้อ 12) --- ## 3. High-level Architecture ```mermaidflowchart LR    C[Clients<br/>X-API-Key] --> LB[Load Balancer]    LB --> GW1[Gateway 1<br/>auth · limiter lib · fallback]    LB --> GW2[Gateway 2..19]    LB --> GW20[Gateway 20]     GW1 -- "EVALSHA 1 RTT<br/>deadline 2ms" --> RC[(Redis Cluster<br/>3 primary + 3 replica)]    GW2 --> RC    GW20 --> RC     GW1 --> UP[Upstream services]    GW2 --> UP    GW20 --> UP     ADM[Admin API / Billing] --> PG[(PostgreSQL<br/>plans · api_keys · overrides)]    PG -. "reload ทุก 30s + NOTIFY" .-> GW1    PG -.-> GW2    PG -.-> GW20     GW1 -. metrics .-> OBS[Prometheus / Grafana / Alertmanager]``` **อธิบายสั้นๆ:**- Limiter เป็น **library ใน gateway** ไม่ใช่ service แยก จึงไม่เพิ่ม network hop และไม่มี component ใหม่ให้ล่ม- **Hot path** = auth → resolve rule (memory) → 1 `EVALSHA` ไป Redis → forward/429- **Config** (กฎ) กับ **state** (bucket) แยกกัน: กฎอยู่ PostgreSQL ที่ durable ส่วน bucket อยู่ Redis ที่หายได้โดยไม่เสียหาย (bucket หาย = เต็ม)- Redis เป็น **ตัวช่วยความแม่นยำ** ไม่ใช่ dependency ที่ API ขาดไม่ได้: ล่มแล้ว gateway ยังตัดสินเองได้ --- ## 4. Component Responsibilities | Component | หน้าที่ | Stateful? | ถ้าล่ม ||---|---|---|---|| Load Balancer | กระจาย request ไป gateway ให้เท่าๆ กัน | ไม่ | Redundant pair / managed LB || API Gateway (x20) | Auth, resolve rule, เรียก limiter, ตอบ 429, forward | ไม่ (มีแค่ cache) | LB ตัดออก ที่เหลือรับแทน, `N` ของ fallback ปรับตาม instance ที่ healthy || Limiter library | Token bucket ผ่าน Redis + breaker + local fallback | Local fallback state (ทิ้งได้) | ตายไปพร้อม gateway ไม่มี state สำคัญ || Redis Cluster | เก็บ bucket, รัน Lua แบบ atomic | ใช่ (สร้างใหม่ได้) | Breaker OPEN → local fallback `limit/N` API ยังทำงาน, shard failover ~ไม่กี่วินาที || Config cache (ใน gateway) | กฎของทุก key ใน memory | ใช่ (สร้างใหม่ได้) | Restart แล้วโหลดใหม่จาก PostgreSQL ถ้าโหลดไม่ได้ใช้กฎ default || PostgreSQL (config) | Source of truth ของ plan/override | ใช่ | Gateway ใช้ config ล่าสุดใน memory ต่อ (last known good) แค่แก้ limit ไม่ได้ชั่วคราว || Admin API | แก้ plan/override แล้ว `NOTIFY` | ไม่ | แก้ limit ไม่ได้ ไม่กระทบ traffic || Monitoring | Metric, alert | – | มองไม่เห็นแต่ traffic ปกติ | --- ## 5. Data Model ### 5.1 Redis (state ของ bucket) ```textKey:    rl:{<api_key_id>}            ← hash tag {...} ให้กฎทุกตัวของ key เดียวกันอยู่ slot เดียวType:   HASHFields: tokens  float   token คงเหลือ ณ เวลา ts        ts      int     เวลาที่อัปเดตล่าสุด (ms, จาก Redis TIME)TTL:    ceil(capacity / rate) + 1s   ← bucket ว่างนานพอจะเต็มเอง ลบทิ้งได้โดยไม่เสียความถูกต้อง rl:ip:{<ip>}                         ← request ที่ยังไม่ผ่าน auth``` - ใช้ `api_key_id` (UUID) ไม่ใช้ secret ดิบ เพราะ key ใน Redis ถูก log หรือ dump ได้- capacity และ rate **ไม่เก็บใน Redis** แต่ส่งผ่าน `ARGV` ทุกครั้ง → เปลี่ยน plan แล้วไม่ต้อง migrate bucket- `maxmemory-policy volatile-ttl` + alert ถ้า `evicted_keys > 0` (bucket ถูก evict = เต็ม = over-admit) ### 5.2 PostgreSQL (config ของกฎ) ```mermaiderDiagram    PLAN ||--o{ API_KEY : "assigned to"    API_KEY ||--o| RATE_LIMIT_OVERRIDE : "may have"     PLAN {        text id PK        int limit_per_min        int burst    }    API_KEY {        uuid id PK        bytea key_hash UK        uuid tenant_id        text plan_id FK        text status "ACTIVE|REVOKED"    }    RATE_LIMIT_OVERRIDE {        uuid api_key_id PK        int limit_per_min        int burst        timestamptz expires_at    }``` ```sqlCREATE TABLE plans (  id            text PRIMARY KEY,  limit_per_min int  NOT NULL CHECK (limit_per_min > 0),  burst         int  NOT NULL CHECK (burst > 0)); CREATE TABLE api_keys (  id         uuid PRIMARY KEY,  key_hash   bytea NOT NULL UNIQUE,   -- sha256(secret)  tenant_id  uuid  NOT NULL,  plan_id    text  NOT NULL REFERENCES plans (id),  status     text  NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'REVOKED')),  updated_at timestamptz NOT NULL DEFAULT now()); CREATE TABLE rate_limit_overrides (  api_key_id    uuid PRIMARY KEY REFERENCES api_keys (id),  limit_per_min int  NOT NULL CHECK (limit_per_min > 0),  burst         int  NOT NULL CHECK (burst > 0),  expires_at    timestamptz,  updated_at    timestamptz NOT NULL DEFAULT now());``` --- ## 6. Bucket & Limiter Lifecycle ### 6.1 Bucket ใน Redis ```mermaidstateDiagram-v2    [*] --> ABSENT    ABSENT --> ACTIVE: request แรก (สร้างเต็ม capacity แล้วหัก cost)    ACTIVE --> ACTIVE: refill ตามเวลา + หัก token    ACTIVE --> EMPTY: token ไม่พอ cost → 429    EMPTY --> ACTIVE: เวลาผ่านไปจน refill พอ    ACTIVE --> ABSENT: PEXPIRE (ว่างนานจนเต็ม) / evict / failover    note right of ABSENT        ABSENT มีความหมายเท่ากับ "bucket เต็ม"        key หาย = over-admit ได้ไม่เกิน 1 burst    end note``` ### 6.2 Circuit breaker ต่อ gateway ```mermaidstateDiagram-v2    [*] --> CLOSED    CLOSED --> OPEN: timeout/error ติดกัน ≥ 5 ครั้ง    OPEN --> HALF_OPEN: ครบ cooldown 1s    HALF_OPEN --> CLOSED: probe สำเร็จ    HALF_OPEN --> OPEN: probe ล้ม    note right of OPEN        ไม่ส่ง request ไป Redis        ตัดสินด้วย local limiter (limit / N)    end note``` --- ## 7. API Design Limiter ไม่มี API ของตัวเอง แต่กำหนด **contract** ของทุก endpoint ที่ผ่าน gateway: | Status / Header | ความหมาย ||---|---|| `X-RateLimit-Limit: 1000` | limit ของ key นี้ต่อ window || `X-RateLimit-Remaining: 998` | token ที่เหลือหลัง request นี้ || `429 Too Many Requests` | เกิน limit (request **ไม่** ถูกส่งต่อ upstream) || `Retry-After: 2` | วินาทีที่ควรรอก่อนลองใหม่ (คำนวณจาก token ที่ขาด / rate) | ```httpHTTP/1.1 429 Too Many RequestsRetry-After: 2X-RateLimit-Limit: 1000X-RateLimit-Remaining: 0Content-Type: application/json { "code": "RATE_LIMITED", "message": "too many requests" }``` Admin API (ภายใน): | Method | Path | ผลลัพธ์ ||---|---|---|| `PUT` | `/admin/api-keys/{id}/override` | ตั้ง override (limit, burst, expires_at) แล้ว `NOTIFY rate_limit_changed` || `GET` | `/admin/api-keys/{id}/usage` | อ่าน bucket ปัจจุบันจาก Redis (debug/support) | --- ## 8. Data Flow: Happy Path ```mermaidsequenceDiagram    autonumber    participant C as Client    participant GW as Gateway (1 ใน 20)    participant CFG as Config cache (memory)    participant R as Redis Cluster    participant UP as Upstream     C->>GW: GET /v1/orders (X-API-Key)    GW->>GW: auth → api_key_id    GW->>CFG: resolve rule (~µs ไม่มี I/O)    GW->>R: EVALSHA token_bucket rl:{key_id} [1000, 0.0167, 1]    R-->>GW: {1, 998, 0} (~0.3–0.8ms)    GW->>UP: forward    UP-->>GW: 200    GW-->>C: 200 + X-RateLimit-Remaining: 998``` --- ## 9. Rate Limiting Algorithm & Atomicity ### 9.1 เลือก algorithm | Algorithm | ข้อดี | ปัญหา | ใช้ไหม ||---|---|---|---|| Fixed window (`INCR` ต่อนาที) | ง่ายที่สุด | Boundary burst 2 เท่า (1,000 ที่ 00:59 + 1,000 ที่ 01:00) | ไม่ || Sliding window log (ZSET) | แม่น 100% | Memory O(limit) ต่อ key (1,000 entry ต่อ key) | เฉพาะ limit ต่ำ (OTP/login) || Sliding window counter | ประหยัด, คลาดน้อย | เป็นค่าประมาณ ต้องจัดการ 2 key | ทางเลือกที่ดี || **Token bucket** | 2 ค่าต่อ key, burst ชัดเจน, rate เฉลี่ยตรง, ใส่ cost ได้ | ต้องคำนวณ refill | **เลือก** | ### 9.2 วิธีที่ผิด: read-modify-write ข้าม network ```go// ❌ Gateway 1 และ 2 อ่านได้ tokens = 1 พร้อมกัน แล้วต่างคนต่างเขียน 0 → ผ่านทั้งคู่tokens, _ := rdb.Get(ctx, key).Int()if tokens > 0 {	rdb.Set(ctx, key, tokens-1, 0)	return true}return false``` ### 9.3 วิธีที่ถูก: Lua script เดียว Redis รัน script **ทีละตัวจนจบ** ไม่มี command อื่นแทรกกลาง การ refill + check + decrement จึง atomic โดยไม่ต้องใช้ lock ```lua-- token_bucket.lua-- KEYS[1] = rl:{<api_key_id>}-- ARGV[1] = capacity, ARGV[2] = rate (token/ms), ARGV[3] = cost-- return {allowed 0|1, remaining, retry_after_ms}local capacity = tonumber(ARGV[1])local rate     = tonumber(ARGV[2])local cost     = tonumber(ARGV[3]) -- นาฬิกาของ Redis ตัวเดียว (ไม่ใช้เวลาของ gateway 20 เครื่องที่ skew กันได้)local t   = redis.call('TIME')local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000) local state  = redis.call('HMGET', KEYS[1], 'tokens', 'ts')local tokens = tonumber(state[1])local ts     = tonumber(state[2])if tokens == nil or ts == nil then  tokens, ts = capacity, nowend tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate) local allowed, retry_after = 0, 0if tokens >= cost then  tokens  = tokens - cost  allowed = 1else  retry_after = math.ceil((cost - tokens) / rate)   -- request ที่ถูกปฏิเสธไม่หัก tokenend redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate) + 1000)return {allowed, math.floor(tokens), retry_after}``` ```gopackage ratelimit import (	"context"	_ "embed"	"time" 	"github.com/redis/go-redis/v9") //go:embed token_bucket.luavar tokenBucketSrc string // Run ใช้ EVALSHA ก่อน ถ้าเจอ NOSCRIPT (Redis restart/failover) จะส่ง EVAL ให้อัตโนมัติvar tokenBucket = redis.NewScript(tokenBucketSrc) type Rule struct {	Limit  int	Window time.Duration	Burst  int} type Decision struct {	Allowed    bool	Remaining  int	RetryAfter time.Duration	Degraded   bool} type RedisLimiter struct {	rdb      redis.UniversalClient	timeout  time.Duration // 2ms	breaker  *Breaker	fallback *LocalFallback} func (l *RedisLimiter) Allow(ctx context.Context, keyID string, rule Rule, cost int) Decision {	if !l.breaker.Ready() {		return l.fallback.Allow(keyID, rule, cost) // OPEN: ไม่เสีย 2ms รอ Redis ที่ล่ม	}	ctx, cancel := context.WithTimeout(ctx, l.timeout)	defer cancel() 	ratePerMs := float64(rule.Limit) / float64(rule.Window.Milliseconds())	res, err := tokenBucket.Run(ctx, l.rdb, []string{"rl:{" + keyID + "}"},		rule.Burst, ratePerMs, cost).Int64Slice()	if err != nil || len(res) != 3 {		l.breaker.Failure()		return l.fallback.Allow(keyID, rule, cost) // fail-open แบบมีเพดาน	}	l.breaker.Success()	return Decision{		Allowed:    res[0] == 1,		Remaining:  int(res[1]),		RetryAfter: time.Duration(res[2]) * time.Millisecond,	}}``` Redis client ตั้งค่าให้เคารพ budget: `ContextTimeoutEnabled: true`, `ReadTimeout/WriteTimeout/PoolTimeout = 2ms`,`MinIdleConns` อุ่น connection ไว้ และ `MaxRetries: -1` (ห้าม retry เพราะจะเกิน budget) ### 9.4 Sequence ตอน 2 gateway แย่ง token ตัวสุดท้าย ```mermaidsequenceDiagram    participant G1 as Gateway 1    participant G2 as Gateway 2    participant R as Redis (single-threaded)     Note over R: rl:{k} tokens = 1    par request พร้อมกัน        G1->>R: EVALSHA token_bucket (cost 1)        G2->>R: EVALSHA token_bucket (cost 1)    end    Note over R: script รันทีละตัวจนจบ    R-->>G1: {1, 0, 0} allowed    R-->>G2: {0, 0, 60} denied    G1->>G1: forward upstream    G2->>G2: 429 + Retry-After: 1``` --- ## 10. Client Contract & Retry (429 / Retry-After) Rate limiter ไม่มีปัญหา "ทำซ้ำแล้วเกิดผลซ้ำ" แบบระบบเงิน แต่มีปัญหาคู่กันคือ **retry ทำให้ load ทวีคูณ**: - Request ที่ถูก 429 **ไม่หัก token** (script หักเฉพาะตอน allowed) ไม่อย่างนั้น client ที่ retry ถี่จะถูกล็อกไม่มีวันหลุด- ส่ง `Retry-After` เสมอ SDK ทางการทำ **exponential backoff + jitter** และเคารพ `Retry-After`- Gateway จำ "key นี้ถูกปฏิเสธถึง t" (negative cache 50–100ms) ลดการถาม Redis ซ้ำจาก client ที่ไม่เคารพ `Retry-After`- Retry ของ client นับเป็น request ใหม่ (ต้องกิน token) เพราะ upstream ต้องทำงานจริงทุกครั้ง ส่วน idempotency ของ business เป็นหน้าที่ของ upstream- Limit ต่อ IP/connection ที่ edge (LB/WAF) เป็นอีกชั้นสำหรับ traffic ที่ตั้งใจโจมตี ```tsasync function callApi(url: string, init: RequestInit, maxAttempts = 4) {  for (let attempt = 1; ; attempt++) {    const res = await fetch(url, init);    if (res.status !== 429 || attempt === maxAttempts) return res;     const retryAfter = Number(res.headers.get("Retry-After") ?? "1");    const base = Math.max(retryAfter, 2 ** (attempt - 1)) * 1_000;    const jitter = Math.random() * base * 0.3; // client หลายตัวไม่ยิงกลับพร้อมกัน    await new Promise((resolve) => setTimeout(resolve, base + jitter));  }}``` --- ## 11. Failure Handling ### 11.1 Failure Matrix | # | สถานการณ์ | ความเสี่ยง | กลไกที่ป้องกัน | ผลลัพธ์ ||---|---|---|---|---|| F1 | 2 gateway หัก token พร้อมกัน | Over-admit ตามจำนวน gateway | Lua script atomic | ผ่านตาม limit พอดี || F2 | Redis ช้า (p99 พุ่ง) | Latency เกิน 2ms | Deadline 2ms + ไม่ retry → local fallback | Latency ไม่เกิน budget, ตัดสินแบบ degraded เฉพาะ request นั้น || F3 | Redis ล่มทั้ง cluster | API ล่มตาม (SPOF) | Breaker OPEN + local limiter `limit/N` | API ทำงานต่อ, limit รวม ≈ 1,000 ถ้า LB กระจายเท่ากัน || F4 | Shard failover (async replication) | Write ล่าสุดหาย bucket มี token มากเกิน | ยอมรับ + `max(0, now - ts)` กันเวลาย้อน | Over-admit ≤ 1 burst ต่อ key ต่อ failover || F5 | Partition: 5/20 gateway เข้าถึง Redis ไม่ได้ | ตัดสินไม่ตรงกัน | 5 ตัวใช้ fallback 50/นาที | รวมสูงสุด ~1,250/นาที (+25%) + alert || F6 | Clock skew ระหว่าง gateway | Refill ผิด | ใช้ `redis.call('TIME')` ใน script | ไม่ขึ้นกับนาฬิกา gateway || F7 | `NOSCRIPT` หลัง Redis restart/failover | Error ทุก request | `Script.Run` fallback เป็น `EVAL` แล้ว cache ใหม่ | 1 RTT เพิ่มครั้งเดียว || F8 | Key ถูก evict (memory เต็ม) | Bucket รีเซ็ตเป็นเต็ม | ทุก key มี TTL, `volatile-ttl`, alert `evicted_keys` | ไม่ควรเกิด ถ้าเกิดก็ over-admit ≤ 1 burst || F9 | Hot key (1 key 1,000 rps) บน shard เดียว | CPU shard เต็ม ทุก key บน shard ช้า | Quota leasing สำหรับ key ใหญ่ + negative cache | Redis call ของ key นั้นลด ~98% || F10 | PostgreSQL (config) ล่ม | โหลดกฎใหม่ไม่ได้ | Last known good ใน memory | Traffic ปกติ แก้ limit ไม่ได้ชั่วคราว || F11 | Gateway restart (config ยังไม่โหลด) | ไม่รู้กฎของ key | ไม่รับ traffic จนกว่า readiness ผ่าน (โหลดกฎแล้ว) | ไม่มีช่วงที่ใช้กฎผิด || F12 | Client retry storm หลัง 429 | Load ทวีคูณ | Retry-After + backoff + ไม่หัก token + negative cache | Load ของการปฏิเสธต่ำ || F13 | จำนวน gateway เปลี่ยน (autoscale) | `limit/N` ของ fallback ผิด | `N` มาจาก service discovery | Fallback ปรับตามจำนวนจริง | ### 11.2 Sequence: Redis ล่ม (เคสที่โจทย์ถามตรงๆ) ```mermaidsequenceDiagram    autonumber    participant C as Client    participant GW as Gateway    participant BR as Breaker    participant R as Redis    participant LF as Local fallback (limit/N)     C->>GW: request    GW->>BR: Ready?    BR-->>GW: CLOSED    GW->>R: EVALSHA (deadline 2ms)    R--xGW: timeout    GW->>BR: Failure() ครบ 5 ครั้ง → OPEN 1s    GW->>LF: Allow(key, 1000/20 = 50 ต่อนาที)    LF-->>GW: allowed (degraded)    GW-->>C: 200 (metric limiter_degraded +1)    Note over GW,R: ระหว่าง OPEN ไม่ยิง Redis เลย latency เพิ่ม ≈ 0    loop ทุก cooldown 1s        GW->>R: probe 1 request (HALF_OPEN)        alt สำเร็จ            GW->>BR: Success() → CLOSED        else ล้ม            GW->>BR: คง OPEN อีก 1s        end    end``` ### 11.3 Code: Breaker + Local fallback ```gotype Breaker struct {	failures  atomic.Int32	openUntil atomic.Int64 // unix nano, 0 = CLOSED	threshold int32	cooldown  time.Duration} func (b *Breaker) Ready() bool {	until := b.openUntil.Load()	if until == 0 {		return true	}	now := time.Now().UnixNano()	if now < until {		return false	}	// HALF_OPEN: ให้ goroutine เดียวเป็น probe	return b.openUntil.CompareAndSwap(until, now+int64(b.cooldown))} func (b *Breaker) Success() {	if b.failures.Load() != 0 {		b.failures.Store(0)	}	if b.openUntil.Load() != 0 {		b.openUntil.Store(0)	}} func (b *Breaker) Failure() {	if b.failures.Add(1) >= b.threshold {		b.openUntil.Store(time.Now().Add(b.cooldown).UnixNano())		b.failures.Store(0)	}} // LocalFallback: golang.org/x/time/rate ต่อ key, limit หารด้วยจำนวน gateway ที่ healthyfunc (f *LocalFallback) Allow(keyID string, rule Rule, cost int) Decision {	n := max(f.instances(), 1)	perSec := float64(rule.Limit) / rule.Window.Seconds() / float64(n) 	f.mu.Lock()	e, ok := f.limiters[keyID] // production ใช้ LRU จำกัดขนาด	if !ok || e.rule != rule || e.n != n {		e = &fallbackEntry{lim: rate.NewLimiter(rate.Limit(perSec), max(rule.Burst/n, 1)), rule: rule, n: n}		f.limiters[keyID] = e	}	f.mu.Unlock() 	if e.lim.AllowN(time.Now(), cost) {		return Decision{Allowed: true, Remaining: int(e.lim.Tokens()), Degraded: true}	}	return Decision{		Allowed:    false,		RetryAfter: time.Duration(float64(cost) / perSec * float64(time.Second)),		Degraded:   true,	}}``` > **ทำไมไม่ fail-open แบบปล่อยหมด:** ช่วงที่ Redis ล่มคือช่วงที่ลูกค้า abuse ได้ง่ายที่สุด และ upstream ไม่มีตัวป้องกันเลย> local limiter ให้ทั้ง availability และยังมีเพดาน ส่วน **fail-closed** (429 ทุก request) ขัดกับโจทย์ตรงๆ --- ## 12. Scaling & Observability ### Scaling- **Redis:** เริ่ม 3 primary รับได้ ~150–300k scripts/s เพิ่ม shard ด้วย online resharding bucket ย้ายตาม slot- **ห้ามอ่าน bucket จาก replica:** replica ใช้ failover เท่านั้น (อ่านค่าเก่า = over-admit)- **Hot key:** key ที่ rate ต่อ instance สูง (เช่น ≥ 10 rps) เปลี่ยนไปใช้ **quota leasing**: gateway ยืม token เป็นก้อน  (chunk = rate ต่อ instance × lease 1s แต่ไม่เกิน burst/(4N)) มาตัดใน memory แล้วเติมแบบ async  → Redis call ลดจาก 1,000/s เหลือ ~20/s ต่อ key ยอม under-admit เล็กน้อยเมื่อ token ค้างใน instance ที่ไม่มี traffic- **Limit ต่ำที่ต้องแม่น 100%** (OTP 3 ครั้ง/10 นาที): ใช้ sliding window log (ZSET) แยกต่างหาก- **Gateway เพิ่ม:** ไม่กระทบ Redis logic เพราะ state อยู่กลาง มีแค่ `N` ของ fallback ที่ปรับตาม discovery- **Multi-region:** แต่ละ region มี Redis ของตัวเอง แบ่ง quota ตามสัดส่วน traffic และ sync แบบ async (ห้ามเรียก Redis ข้าม region บน hot path) ### Observability | Metric / Alert | ทำไม ||---|---|| `ratelimit_check_seconds` p99 (SLO < 2ms) | พิสูจน์ NFR เรื่อง latency || `ratelimit_decisions_total{result, plan, mode}` | อัตรา 429 ต่อ plan และสัดส่วนที่ตัดสินแบบ `degraded` || `ratelimit_breaker_state` ต่อ gateway | รู้ทันทีว่า gateway ไหนตัดขาด Redis || Redis CPU ต่อ shard, `instantaneous_ops_per_sec` | เห็น hot shard/hot key ก่อนกระทบ latency || `redis_evicted_keys_total` ต้องเป็น 0 | bucket ถูก evict = over-admit || Top-N key ที่ถูก 429 มากที่สุด | support ลูกค้าและจับ abuse | --- ## 13. Trade-offs & Alternatives | การตัดสินใจ | สิ่งที่เลือก | ทางเลือกอื่น | เหตุผล / สิ่งที่ยอมเสีย ||---|---|---|---|| Algorithm | Token bucket | Fixed window, sliding log, sliding counter | ไม่มี boundary burst และใช้ memory น้อย แต่ต้องอธิบาย burst ให้ลูกค้าเข้าใจ || ที่เก็บ state | Redis Cluster กลาง | Local ต่อ gateway อย่างเดียว | แม่นยำข้าม 20 instance แต่ต้องมี 1 RTT ต่อ request || Atomicity | Lua script | `MULTI/WATCH`, distributed lock | 1 RTT และไม่มี retry loop แต่ script ต้องสั้น (block Redis ระหว่างรัน) || นาฬิกา | Redis `TIME` | เวลาของ gateway | ไม่มี clock skew แต่ผูกกับเวลาของ primary (failover อาจเลื่อน → clamp ด้วย max 0) || ตอน Redis ล่ม | Fail-open แบบมีเพดาน (limit/N) | Fail-closed, fail-open เต็ม | API ยังใช้ได้และยังมีเพดาน ยอมคลาดเมื่อ LB กระจายไม่เท่ากัน || Durability ของ bucket | ไม่ต้อง durable (หายได้) | AOF always / `WAIT` | Latency ต่ำ ยอม over-admit ≤ 1 burst ตอน failover || Deploy | Library ใน gateway | Rate limit service แยก | ไม่มี hop และ SPOF เพิ่ม แต่ต้อง deploy library ไปทุก gateway เมื่อแก้ || Key ใหญ่ | Quota leasing (แนวทาง B) | เพิ่ม shard | Shard เพิ่มไม่ช่วย hot key เดียว ยอม under-admit เล็กน้อย || Limit ต่ำที่ต้องแม่น | Sliding log (แนวทาง C) | Token bucket | แม่น 100% แต่ memory O(limit) จึงใช้เฉพาะ OTP/login | **ถ้ามีเวลามากกว่านี้:** limit หลายชั้นพร้อมกันใน script เดียว (ต่อวินาที/นาที/วัน), cost-based limit (เช่น นับ token ของ LLM),concurrency limit (in-flight) และ quota ต่อ tenant ที่มีหลาย key --- ## References - Redis: Scripting with Lua: https://redis.io/docs/latest/develop/interact/programmability/eval-intro/- Stripe: Scaling your API with rate limiters: https://stripe.com/blog/rate-limiters- Cloudflare: How we built rate limiting capable of scaling to millions of domains: https://blog.cloudflare.com/counting-things-a-lot-of-different-things/- RFC 6585 (429 Too Many Requests): https://www.rfc-editor.org/rfc/rfc6585- golang.org/x/time/rate: https://pkg.go.dev/golang.org/x/time/rate

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

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

N1 · เทียบ algorithm และ sliding window counter

Fixed window ง่ายแต่มี boundary burst, sliding log แม่นแต่เปลือง memory ทางสายกลางที่ Cloudflare ใช้คือ sliding window counter: เก็บ counter ของ window ปัจจุบันและก่อนหน้า แล้วถ่วงน้ำหนักตามเวลาที่เหลือ คลาดได้เล็กน้อยเพราะสมมติว่า request ใน window ก่อนหน้ากระจายเท่าๆ กัน ส่วน GCRA ให้ผลเทียบเท่า token bucket แต่เก็บค่าเดียว (theoretical arrival time) เหมาะเมื่ออยากประหยัด memory สุดๆ ในห้องสอบให้เลือก token bucket เพราะอธิบาย burst กับ rate ได้ตรงที่สุด

sliding_counter.lua
-- sliding window counter (Cloudflare style): 2 counter ต่อ key ประหยัดกว่า log มาก
-- estimate = prev × (เวลาที่เหลือของ window ก่อนหน้า / window) + curr
local window = tonumber(ARGV[1])        -- ms
local limit  = tonumber(ARGV[2])
local t   = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local cur_start = now - (now % window)

local curr_key = KEYS[1] .. ':' .. cur_start
local prev_key = KEYS[1] .. ':' .. (cur_start - window)
local curr = tonumber(redis.call('GET', curr_key) or '0')
local prev = tonumber(redis.call('GET', prev_key) or '0')

local weight   = (window - (now - cur_start)) / window
local estimate = prev * weight + curr
if estimate + 1 > limit then
  return 0
end
redis.call('INCR', curr_key)
redis.call('PEXPIRE', curr_key, window * 2)  -- INCR + PEXPIRE อยู่ใน script เดียว = atomic
return 1
-- หมายเหตุ: script สร้างชื่อ key เองจึงใช้ได้แค่ Redis เดี่ยว
-- บน Cluster ต้องส่งทั้ง 2 key มาใน KEYS และใส่ hash tag เดียวกัน

N2 · Redis Cluster, hash tag และ hot key

Redis Cluster แบ่ง key เป็น 16,384 slot ตาม CRC16 ของชื่อ key (หรือของ ส่วนใน {…}) script ที่ใช้หลาย key ต้องให้ทุก key อยู่ slot เดียว ไม่อย่างนั้นจะได้ CROSSSLOT error และจุดที่คนมักพลาดคือคิดว่าเพิ่ม shard แล้วจะแก้ hot key ได้ แต่ key เดียวอยู่ได้ shard เดียวเสมอ

cluster.txt
Redis Cluster: 16,384 slot, key → slot = CRC16(key) mod 16384

  rl:{key-123}              → slot ของ "key-123"
  rl:{key-123}:POST:/orders → slot เดียวกัน (hash tag เหมือนกัน)

- 50k key กระจายเกือบเท่ากันบน 3 primary (~33k key/shard)
- 1 key ใช้ได้ 1 shard เท่านั้น: key เดียวที่ 60,000 rps → shard นั้น CPU เต็ม (hot key)
  ทางแก้: แนวทาง B (leasing) สำหรับ key ใหญ่,
          หรือ negative cache "key นี้ถูก 429 ถึง t" ใน gateway 50–100ms
- เพิ่ม shard: resharding ย้าย slot ได้ online, bucket ย้ายตามไปด้วย
- Replica ไว้ failover เท่านั้น: ห้ามอ่าน bucket จาก replica (stale = over-admit)

N3 · เวลา, script replication และ failover

ถ้าให้ gateway ส่ง now เข้า script เครื่องที่นาฬิกาเร็วจะ refill เกิน เครื่องที่ช้าจะได้ elapsed ติดลบ จึงใช้ redis.call('TIME') ใน script ใน Redis 7 script ถูก replicate แบบ effects (ส่งผลลัพธ์ของ write ไป replica ไม่ได้ให้ replica รัน script ซ้ำ) จึงเรียกคำสั่งที่ไม่ deterministic อย่าง TIME ก่อน write ได้ ส่วน Redis เวอร์ชันเก่าต้องเรียก redis.replicate_commands() ก่อน หลัง failover นาฬิกาของ primary ใหม่อาจต่างจากเดิมเล็กน้อย max(0, now - ts) กันไม่ให้ token ติดลบ

Replication ของ Redis เป็น async write ที่ ack แล้วอาจหายตอน failover สำหรับ rate limiter ผลคือ bucket บางตัวมี token มากเกินจริง ซึ่งยอมรับได้ ถ้าจะบังคับด้วย WAIT จะเพิ่ม latency ทุก request และเกิน budget

N4 · ขอบเขตความคลาดเคลื่อนในแต่ละสถานการณ์

คำว่า "แม่นยำพอสมควร" ต้องตอบเป็นตัวเลขทุกสถานการณ์:

  • ปกติ (A): ไม่เกิน burst + rate × T เลย เพราะผู้ตัดสินมีตัวเดียวและ atomic
  • Redis ล่มทั้งหมด: gateway N ตัว × (limit/N) = limit ถ้า LB กระจายเท่ากัน ถ้าไม่เท่ากัน key หนึ่งอาจถูก 429 เร็วขึ้นบน instance ที่ traffic หนาแน่น (under-admit ไม่ใช่ over)
  • Partition k จาก N ตัว: เกินได้ไม่เกิน k × limit/N เช่น 5 จาก 20 = +25%
  • Failover: เกินได้ ≤ 1 burst ต่อ key ต่อครั้ง
  • Leasing (B): เกินได้ ≤ stock ที่ค้างทั้ง fleet (≤ burst/4 เมื่อจำกัด chunk ≤ burst/(4N))

N5 · พิสูจน์ว่าแม่นและเร็วจริง

ทดสอบความแม่นยำด้วย integration test ที่จำลอง 20 gateway ยิง key เดียวกันพร้อมกัน แล้วตรวจว่าผ่านไม่เกิน burst + rate × elapsed และไม่ต่ำกว่า burst (ไม่มี under-admit) ใน production ให้วัดด้วย metric ต่อไปนี้ และทำ chaos test ด้วยการปิด Redis ใน staging เพื่อดูว่า API ไม่ล่มและ breaker เปิด/ปิดตามที่คาด

limiter_test.go
// Integration test: 20 goroutine จำลอง 20 gateway ยิง key เดียวกันพร้อมกัน
// ต้องไม่ปล่อยเกิน burst + rate × elapsed (ไม่มี over-admit จาก race)
func TestTokenBucketNoOverAdmission(t *testing.T) {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		t.Skip("REDIS_ADDR not set")
	}
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	lim := &RedisLimiter{
		rdb:      rdb,
		timeout:  50 * time.Millisecond, // ในเทสต์ห้ามตกไป fallback
		breaker:  &Breaker{threshold: 1_000_000, cooldown: time.Second},
		fallback: &LocalFallback{limiters: map[string]*fallbackEntry{}, instances: func() int { return 20 }},
	}
	rule := Rule{Limit: 1000, Window: time.Minute, Burst: 1000}
	keyID := "test-" + strconv.FormatInt(time.Now().UnixNano(), 10)

	var allowed, degraded atomic.Int64
	start := time.Now()
	var wg sync.WaitGroup
	for g := 0; g < 20; g++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 200; i++ { // รวม 4,000 request
				d := lim.Allow(context.Background(), keyID, rule, 1)
				if d.Allowed {
					allowed.Add(1)
				}
				if d.Degraded {
					degraded.Add(1)
				}
			}
		}()
	}
	wg.Wait()

	elapsed := time.Since(start)
	upper := float64(rule.Burst) + float64(rule.Limit)*elapsed.Seconds()/rule.Window.Seconds()
	if degraded.Load() != 0 {
		t.Fatalf("unexpected degraded decisions: %d", degraded.Load())
	}
	if got := float64(allowed.Load()); got > upper || got < float64(rule.Burst) {
		t.Fatalf("allowed=%v want between %d and %.0f", got, rule.Burst, upper)
	}
}
alerts.promql
# สัดส่วน request ที่ถูก 429 ต่อ plan (ใช้คุยกับ product/ลูกค้า)
sum by (plan) (rate(ratelimit_decisions_total{result="denied"}[5m]))
  / sum by (plan) (rate(ratelimit_decisions_total[5m]))

# latency ที่ limiter เพิ่มเข้าไป (SLO: p99 < 2ms)
histogram_quantile(0.99, sum by (le) (rate(ratelimit_check_seconds_bucket[5m])))

# ช่วงที่ตัดสินด้วย fallback (Redis มีปัญหา) → ควรเป็น 0 เกือบตลอด
sum(rate(ratelimit_decisions_total{mode="degraded"}[1m]))

# Redis ฝั่ง server: evicted_keys ต้องเป็น 0 (bucket ถูก evict = over-admit)
increase(redis_evicted_keys_total[10m]) > 0

N6 · คำศัพท์

คำความหมาย
Token bucket

ถังจุ token ได้ไม่เกิน capacity เติมด้วย rate คงที่ 1 request ใช้ cost token

Burst

จำนวน request ที่ผ่านติดกันได้ทันทีเมื่อ bucket เต็ม (= capacity)

Boundary burst

ปัญหา fixed window ที่ยิงคร่อมขอบ window แล้วผ่านได้เกือบ 2 เท่าของ limit

GCRA

Generic Cell Rate Algorithm เทียบเท่า token bucket แต่เก็บค่าเดียวคือ theoretical arrival time

Fail-open / Fail-closed

เมื่อผู้ตัดสินล่ม เลือกปล่อยผ่าน (availability) หรือปฏิเสธ (safety)

Circuit breaker

หยุดเรียก dependency ที่ล้มชั่วคราว แล้วค่อย probe ว่ากลับมาหรือยัง

Quota leasing

ยืม token จากที่เก็บกลางเป็นก้อนมาใช้ใน local เพื่อลด round trip

Hash tag

ส่วน {…} ในชื่อ key ของ Redis Cluster ที่ใช้คำนวณ slot ทำให้หลาย key อยู่ node เดียว

Hot key

key เดียวที่ traffic สูงจน shard ที่ถือมันเป็นคอขวด เพิ่ม shard ก็ไม่ช่วย

อ่านเอกสารทางการ: Scripting with Lua (Redis) ↗
อ่านเอกสารทางการ: Scaling your API with rate limiters (Stripe) ↗
อ่านเอกสารทางการ: Sliding window counter (Cloudflare) ↗
อ่านเอกสารทางการ: RFC 6585: 429 Too Many Requests ↗