บทที่ 10: Caching
“ทุกครั้งที่อยากกินน้ำเย็น ไม่ต้องไปซื้อที่ร้านสะดวกซื้อ แค่เปิดตู้เย็น”
The Blueprint (พิมพ์เขียว)
Section titled “The Blueprint (พิมพ์เขียว)”ทุกครั้งที่ดึงข้อมูลจาก Database ต้องใช้เวลา:
- Network latency
- Query processing
- Data transfer
Cache = ตู้เย็นติดครัว — เก็บของที่ใช้บ่อยไว้ใกล้มือ
The Construction Site (หน้างานก่อสร้าง)
Section titled “The Construction Site (หน้างานก่อสร้าง)”❄️ ลำดับชั้นของ Cache
Section titled “❄️ ลำดับชั้นของ Cache”📱 Browser Cache (ที่โต๊ะ) ← เร็วสุด ↓🌐 CDN Cache (ร้านหน้าปากซอย) ↓💾 Application Cache / Redis (ตู้เย็น) ↓🗄️ Database (ซุปเปอร์มาร์เก็ต) ← ช้าสุด📊 Cache Hit vs Miss
Section titled “📊 Cache Hit vs Miss”| สถานการณ์ | เวลา | ทำอะไร |
|---|---|---|
| Cache Hit | ~1ms | เจอใน Cache ส่งกลับเลย |
| Cache Miss | ~100ms | ไม่เจอ ต้องไป Database |
Material Selection (เลือกสเปกวัสดุ)
Section titled “Material Selection (เลือกสเปกวัสดุ)”🔴 Redis — Application Cache
Section titled “🔴 Redis — Application Cache”import Redis from 'ioredis';const redis = new Redis();
async function getProducts() { // ลองดึงจาก Cache ก่อน const cached = await redis.get('products'); if (cached) return JSON.parse(cached);
// ถ้าไม่มี ไป Database const products = await db.product.findMany();
// เก็บใน Cache 5 นาที await redis.setex('products', 300, JSON.stringify(products));
return products;}🌐 CDN — ร้านสะดวกซื้อทั่วโลก
Section titled “🌐 CDN — ร้านสะดวกซื้อทั่วโลก”// Next.js - Static Generation with Revalidationexport const revalidate = 3600; // Revalidate ทุก 1 ชั่วโมง
async function ProductPage() { const products = await fetchProducts(); return <ProductList products={products} />;}⚛️ Client-side Cache (SWR/React Query)
Section titled “⚛️ Client-side Cache (SWR/React Query)”import useSWR from 'swr';
function Products() { const { data, error, isLoading } = useSWR('/api/products', fetcher, { revalidateOnFocus: false, dedupingInterval: 60000, // Cache 1 นาที });
if (isLoading) return <Loading />; return <ProductList products={data} />;}Architect’s Note (บันทึกสถาปนิก)
Section titled “Architect’s Note (บันทึกสถาปนิก)”⚠️ ข้อควรระวัง
Section titled “⚠️ ข้อควรระวัง”💡 Best Practices
Section titled “💡 Best Practices”- Cache สิ่งที่ไม่ค่อยเปลี่ยน — Product list, Config
- ตั้ง TTL ที่เหมาะสม — ไม่สั้นไป ไม่นานไป
- Invalidate เมื่อข้อมูลเปลี่ยน — หลัง Update/Delete