์ฝ˜ํ…์ธ  ๋Œ€ํ‘œ ์ด๋ฏธ์ง€ - ๐Ÿš€ Go์–ธ์–ด ์บ์‹ฑ ์ „๋žต ์™„์ „์ •๋ณต: sync.Map๊ณผ Redis๋กœ ์„ฑ๋Šฅ 10๋ฐฐ ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ

๐Ÿš€ Go์–ธ์–ด ์บ์‹ฑ ์ „๋žต ์™„์ „์ •๋ณต: sync.Map๊ณผ Redis๋กœ ์„ฑ๋Šฅ 10๋ฐฐ ๋Œ์–ด์˜ฌ๋ฆฌ๊ธฐ

์•ˆ๋…•! ์˜ค๋Š˜์€ Go ์–ธ์–ด๋กœ ๊ฐœ๋ฐœํ•˜๋ฉด์„œ ๋ˆ„๊ตฌ๋‚˜ ํ•œ ๋ฒˆ์ฏค ๊ณ ๋ฏผํ•˜๊ฒŒ ๋˜๋Š” ์บ์‹ฑ ์ „๋žต์— ๋Œ€ํ•ด ๊นŠ์ด ์žˆ๊ฒŒ ํŒŒํ—ค์ณ๋ณผ ๊ฑฐ์•ผ. ๐ŸŽฏ

์„œ๋น„์Šค๊ฐ€ ์ปค์ง€๋ฉด์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ถ€ํ•˜๊ฐ€ ๊ฑฑ์ •๋˜๊ฑฐ๋‚˜, API ์‘๋‹ต ์†๋„๊ฐ€ ๋А๋ ค์ ธ์„œ ๊ณ ๋ฏผ์ด๋ผ๋ฉด?
์ด ๊ธ€์ด ๋ฐ”๋กœ ๋„ˆ๋ฅผ ์œ„ํ•œ ์†”๋ฃจ์…˜์ด ๋  ๊ฑฐ์•ผ! sync.Map๋ถ€ํ„ฐ Redis ํด๋ผ์ด์–ธํŠธ ์ตœ์ ํ™”๊นŒ์ง€, ์‹ค์ „์—์„œ ๋ฐ”๋กœ ์จ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๋…ธํ•˜์šฐ๋ฅผ ์นœ๊ตฌ์ฒ˜๋Ÿผ ํŽธํ•˜๊ฒŒ ์•Œ๋ ค์ค„๊ฒŒ. ๐Ÿ˜Š

๐Ÿ’ก ์™œ ์บ์‹ฑ์ด ํ•„์š”ํ• ๊นŒ?

๊ฐœ๋ฐœํ•˜๋‹ค ๋ณด๋ฉด ๊ฐ™์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ ์กฐํšŒํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์—„์ฒญ ๋งŽ์•„.
์˜ˆ๋ฅผ ๋“ค์–ด ์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ์ •๋ณด, ์ƒํ’ˆ ๋ชฉ๋ก, ์„ค์ • ๊ฐ’ ๊ฐ™์€ ๊ฒƒ๋“ค ๋ง์ด์•ผ.

๋งค๋ฒˆ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ ‘๊ทผํ•˜๋ฉด ์–ด๋–ค ์ผ์ด ๋ฒŒ์–ด์งˆ๊นŒ? ๐Ÿค”

โš ๏ธ ์บ์‹ฑ ์—†์ด ์šด์˜ํ•  ๋•Œ ๋ฐœ์ƒํ•˜๋Š” ๋ฌธ์ œ๋“ค

โ€ข ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ปค๋„ฅ์…˜ ํ’€ ๊ณ ๊ฐˆ
โ€ข ๋„คํŠธ์›Œํฌ ๋ ˆ์ดํ„ด์‹œ ๋ˆ„์ 
โ€ข CPU ์‚ฌ์šฉ๋ฅ  ๊ธ‰์ฆ
โ€ข ์‘๋‹ต ์‹œ๊ฐ„ ์ง€์—ฐ (์ˆ˜๋ฐฑ ms โ†’ ์ˆ˜์‹ญ ms๋กœ ๊ฐœ์„  ๊ฐ€๋Šฅ!)
โ€ข ์„œ๋ฒ„ ๋น„์šฉ ์ฆ๊ฐ€ ๐Ÿ’ธ

์‹ค์ œ๋กœ ์บ์‹ฑ์„ ์ ์šฉํ•˜๋ฉด ์‘๋‹ต ์†๋„๊ฐ€ 10๋ฐฐ์—์„œ 100๋ฐฐ๊นŒ์ง€ ๋นจ๋ผ์ง€๋Š” ๊ฒฝ์šฐ๋„ ํ”ํ•ด.
ํŠนํžˆ ์ฝ๊ธฐ ์ž‘์—…์ด ๋งŽ์€ ์„œ๋น„์Šค๋ผ๋ฉด ์บ์‹ฑ์€ ์„ ํƒ์ด ์•„๋‹ˆ๋ผ ํ•„์ˆ˜์•ผ!

์žฌ๋Šฅ๋„ท ๊ฐ™์€ ํ”Œ๋žซํผ์—์„œ๋„ ์‚ฌ์šฉ์ž ์ •๋ณด๋‚˜ ์žฌ๋Šฅ ๋ชฉ๋ก์„ ์บ์‹ฑํ•ด์„œ ๋น ๋ฅธ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์„ ๊ฑฐ์•ผ.

์บ์‹ฑ ์ „๋žต ๋น„๊ต ๋กœ์ปฌ ์บ์‹œ sync.Map ์ดˆ๊ณ ์† / ๋‹จ์ผ ์„œ๋ฒ„ ๋ถ„์‚ฐ ์บ์‹œ Redis ๊ณ ์† / ๋‹ค์ค‘ ์„œ๋ฒ„ ํ•˜์ด๋ธŒ๋ฆฌ๋“œ L1 + L2 ์ตœ์  / ๊ณ„์ธต ๊ตฌ์กฐ โšก ๋‚˜๋…ธ์ดˆ ๋‹จ์œ„ ๐ŸŒ ๋งˆ์ดํฌ๋กœ์ดˆ ๋‹จ์œ„ ๐ŸŽฏ ์ƒํ™ฉ๋ณ„ ์ตœ์ ํ™”

๐Ÿ”ฅ Go์˜ sync.Map ์™„์ „ ๋ถ„์„

Go 1.9 ๋ฒ„์ „๋ถ€ํ„ฐ ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— ํฌํ•จ๋œ sync.Map์€ ๋™์‹œ์„ฑ ํ™˜๊ฒฝ์—์„œ ์•ˆ์ „ํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋งต์ด์•ผ.
์ผ๋ฐ˜ map์— mutex๋ฅผ ๊ฑธ์–ด์„œ ์“ฐ๋Š” ๊ฒƒ๋ณด๋‹ค ํŠน์ • ์ƒํ™ฉ์—์„œ ํ›จ์”ฌ ๋น ๋ฅด๊ฑฐ๋“ ! ๐Ÿš€

sync.Map์˜ ๋‚ด๋ถ€ ๊ตฌ์กฐ ์ดํ•ดํ•˜๊ธฐ

sync.Map์€ ๋‚ด๋ถ€์ ์œผ๋กœ read map๊ณผ dirty map ๋‘ ๊ฐœ์˜ ๋งต์„ ๊ด€๋ฆฌํ•ด.
์ด๊ฒŒ ํ•ต์‹ฌ ๋น„๋ฐ€์ธ๋ฐ, ์ฝ๊ธฐ ์ž‘์—…์€ read map์—์„œ ๋ฝ ์—†์ด ์ฒ˜๋ฆฌํ•˜๊ณ ,
์“ฐ๊ธฐ ์ž‘์—…์€ dirty map์— ๋จผ์ € ๊ธฐ๋กํ•œ ๋‹ค์Œ ๋‚˜์ค‘์— read map์œผ๋กœ ์Šน๊ฒฉ์‹œํ‚ค๋Š” ๋ฐฉ์‹์ด์•ผ.

๐ŸŽ“ sync.Map์˜ ์ž‘๋™ ์›๋ฆฌ

1. Read Map (์ฝ๊ธฐ ์ „์šฉ)
โ€ข atomic ์—ฐ์‚ฐ์œผ๋กœ ๋ฝ ์—†์ด ์ ‘๊ทผ
โ€ข ๋Œ€๋ถ€๋ถ„์˜ ์ฝ๊ธฐ ์ž‘์—…์ด ์—ฌ๊ธฐ์„œ ์ฒ˜๋ฆฌ๋จ
โ€ข ์„ฑ๋Šฅ์ด ๊ทน๋„๋กœ ๋น ๋ฆ„ โšก

2. Dirty Map (์“ฐ๊ธฐ์šฉ)
โ€ข ์ƒˆ๋กœ์šด ํ‚ค ์ถ”๊ฐ€ ์‹œ ์‚ฌ์šฉ
โ€ข mutex๋กœ ๋ณดํ˜ธ๋จ
โ€ข ์ผ์ • ์กฐ๊ฑด์ด ๋˜๋ฉด read map์œผ๋กœ ์Šน๊ฒฉ

3. Misses ์นด์šดํ„ฐ
โ€ข read map์—์„œ ๋ชป ์ฐพ์€ ํšŸ์ˆ˜ ์ถ”์ 
โ€ข ์ž„๊ณ„๊ฐ’ ๋„๋‹ฌ ์‹œ dirty โ†’ read ์Šน๊ฒฉ ํŠธ๋ฆฌ๊ฑฐ

sync.Map ์‹ค์ „ ์‚ฌ์šฉ๋ฒ•

์ด๋ก ์€ ์ด ์ •๋„๋กœ ํ•˜๊ณ , ์‹ค์ œ ์ฝ”๋“œ๋กœ ์–ด๋–ป๊ฒŒ ์“ฐ๋Š”์ง€ ๋ณผ๊นŒ?

package main

import (
    "fmt"
    "sync"
    "time"
)

type UserCache struct {
    cache sync.Map
}

type User struct {
    ID       int
    Name     string
    Email    string
    CachedAt time.Time
}

// ์‚ฌ์šฉ์ž ์ •๋ณด ์ €์žฅ
func (uc *UserCache) Set(userID int, user User) {
    user.CachedAt = time.Now()
    uc.cache.Store(userID, user)
}

// ์‚ฌ์šฉ์ž ์ •๋ณด ์กฐํšŒ
func (uc *UserCache) Get(userID int) (User, bool) {
    value, ok := uc.cache.Load(userID)
    if !ok {
        return User{}, false
    }
    
    user := value.(User)
    
    // ์บ์‹œ ๋งŒ๋ฃŒ ์ฒดํฌ (5๋ถ„)
    if time.Since(user.CachedAt) > 5*time.Minute {
        uc.cache.Delete(userID)
        return User{}, false
    }
    
    return user, true
}

// ์‚ฌ์šฉ์ž ์ •๋ณด ์‚ญ์ œ
func (uc *UserCache) Delete(userID int) {
    uc.cache.Delete(userID)
}

// ๋ชจ๋“  ์บ์‹œ ์ˆœํšŒ
func (uc *UserCache) Range(fn func(userID int, user User) bool) {
    uc.cache.Range(func(key, value interface{}) bool {
        return fn(key.(int), value.(User))
    })
}

func main() {
    cache := &UserCache{}
    
    // ๋™์‹œ์— ์—ฌ๋Ÿฌ ๊ณ ๋ฃจํ‹ด์—์„œ ์•ˆ์ „ํ•˜๊ฒŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
    var wg sync.WaitGroup
    
    // ์“ฐ๊ธฐ ์ž‘์—…
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            cache.Set(id, User{
                ID:    id,
                Name:  fmt.Sprintf("User%d", id),
                Email: fmt.Sprintf("user%d@example.com", id),
            })
        }(i)
    }
    
    // ์ฝ๊ธฐ ์ž‘์—…
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            if user, ok := cache.Get(id); ok {
                fmt.Printf("Found: %s\n", user.Name)
            }
        }(i)
    }
    
    wg.Wait()
    
    // ์บ์‹œ๋œ ํ•ญ๋ชฉ ์ˆ˜ ํ™•์ธ
    count := 0
    cache.Range(func(userID int, user User) bool {
        count++
        return true
    })
    fmt.Printf("Total cached users: %d\n", count)
}

๐Ÿ’ก sync.Map ์‚ฌ์šฉ ํŒ

sync.Map์ด ์œ ๋ฆฌํ•œ ๊ฒฝ์šฐ:
โ€ข ์ฝ๊ธฐ ์ž‘์—…์ด ์“ฐ๊ธฐ๋ณด๋‹ค ์••๋„์ ์œผ๋กœ ๋งŽ์„ ๋•Œ
โ€ข ํ‚ค ์ง‘ํ•ฉ์ด ์•ˆ์ •์ ์ด๊ณ  ์ž์ฃผ ๋ณ€ํ•˜์ง€ ์•Š์„ ๋•Œ
โ€ข ์—ฌ๋Ÿฌ ๊ณ ๋ฃจํ‹ด์ด ๋™์‹œ์— ์ ‘๊ทผํ•˜๋Š” ๊ฒฝ์šฐ

์ผ๋ฐ˜ map + mutex๊ฐ€ ๋‚˜์€ ๊ฒฝ์šฐ:
โ€ข ์“ฐ๊ธฐ ์ž‘์—…์ด ๋นˆ๋ฒˆํ•œ ๊ฒฝ์šฐ
โ€ข ํ‚ค๊ฐ€ ๊ณ„์† ์ถ”๊ฐ€/์‚ญ์ œ๋˜๋Š” ๊ฒฝ์šฐ
โ€ข ๋‹จ์ผ ๊ณ ๋ฃจํ‹ด์—์„œ๋งŒ ์ ‘๊ทผํ•˜๋Š” ๊ฒฝ์šฐ

sync.Map vs map + RWMutex ์„ฑ๋Šฅ ๋น„๊ต

์‹ค์ œ๋กœ ์–ผ๋งˆ๋‚˜ ์ฐจ์ด๊ฐ€ ๋‚ ๊นŒ? ๋ฒค์น˜๋งˆํฌ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ํ™•์‹คํžˆ ์•Œ ์ˆ˜ ์žˆ์–ด.

package main

import (
    "sync"
    "testing"
)

// sync.Map ๋ฒ„์ „
func BenchmarkSyncMapRead(b *testing.B) {
    var m sync.Map
    
    // ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ์„ค์ •
    for i := 0; i < 1000; i++ {
        m.Store(i, i*2)
    }
    
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            m.Load(500)
        }
    })
}

// map + RWMutex ๋ฒ„์ „
func BenchmarkRWMutexMapRead(b *testing.B) {
    m := make(map[int]int)
    var mu sync.RWMutex
    
    // ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ์„ค์ •
    for i := 0; i < 1000; i++ {
        m[i] = i * 2
    }
    
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            mu.RLock()
            _ = m[500]
            mu.RUnlock()
        }
    })
}

// ์“ฐ๊ธฐ ์ž‘์—… ๋ฒค์น˜๋งˆํฌ
func BenchmarkSyncMapWrite(b *testing.B) {
    var m sync.Map
    
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            m.Store(i, i*2)
            i++
        }
    })
}

func BenchmarkRWMutexMapWrite(b *testing.B) {
    m := make(map[int]int)
    var mu sync.RWMutex
    
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            mu.Lock()
            m[i] = i * 2
            mu.Unlock()
            i++
        }
    })
}

์œ„ ๋ฒค์น˜๋งˆํฌ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์ด๋Ÿฐ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์™€:

๐Ÿ“Š ์„ฑ๋Šฅ ๋น„๊ต ๊ฒฐ๊ณผ (์ฝ๊ธฐ ์ค‘์‹ฌ ์›Œํฌ๋กœ๋“œ)

sync.Map ์ฝ๊ธฐ: ~20 ns/op
RWMutex ์ฝ๊ธฐ: ~50 ns/op
โ†’ sync.Map์ด ์•ฝ 2.5๋ฐฐ ๋น ๋ฆ„! ๐Ÿš€

sync.Map ์“ฐ๊ธฐ: ~200 ns/op
RWMutex ์“ฐ๊ธฐ: ~150 ns/op
โ†’ ์“ฐ๊ธฐ๋Š” RWMutex๊ฐ€ ์•ฝ๊ฐ„ ์œ ๋ฆฌ

๊ฒฐ๋ก ์ ์œผ๋กœ ์ฝ๊ธฐ๊ฐ€ 90% ์ด์ƒ์ธ ์บ์‹œ ์‹œ๋‚˜๋ฆฌ์˜ค์—์„œ๋Š” sync.Map์ด ํ™•์‹คํ•œ ์Šน์ž์•ผ!

๐ŸŽฏ ์‹ค์ „ ์บ์‹ฑ ํŒจํ„ด ๊ตฌํ˜„ํ•˜๊ธฐ

์ด์ œ ์‹ค๋ฌด์—์„œ ๋ฐ”๋กœ ์“ธ ์ˆ˜ ์žˆ๋Š” ๊ณ ๊ธ‰ ์บ์‹ฑ ํŒจํ„ด๋“ค์„ ์•Œ์•„๋ณผ๊ฒŒ.
๋‹จ์ˆœํžˆ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ๊บผ๋‚ด๋Š” ๊ฒƒ์„ ๋„˜์–ด์„œ, ํšจ์œจ์ ์ด๊ณ  ์•ˆ์ •์ ์ธ ์บ์‹œ ์‹œ์Šคํ…œ์„ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์ด์•ผ.

Cache-Aside ํŒจํ„ด (Lazy Loading)

๊ฐ€์žฅ ๋งŽ์ด ์“ฐ์ด๋Š” ํŒจํ„ด์ด์•ผ. ๋ฐ์ดํ„ฐ๊ฐ€ ํ•„์š”ํ•  ๋•Œ๋งŒ ์บ์‹œ์— ๋กœ๋“œํ•˜๋Š” ๋ฐฉ์‹์ด์ง€.
๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ์“ธ ์ˆ˜ ์žˆ๊ณ , ๊ตฌํ˜„๋„ ์ง๊ด€์ ์ด๋ผ์„œ ์ดˆ๋ณด์ž๋„ ์‰ฝ๊ฒŒ ์ ์šฉํ•  ์ˆ˜ ์žˆ์–ด.

package main

import (
    "database/sql"
    "fmt"
    "sync"
    "time"
)

type CacheAsideStore struct {
    cache      sync.Map
    db         *sql.DB
    ttl        time.Duration
    loadFunc   func(key string) (interface{}, error)
}

type CachedItem struct {
    Value      interface{}
    ExpireTime time.Time
}

func NewCacheAsideStore(db *sql.DB, ttl time.Duration) *CacheAsideStore {
    return &CacheAsideStore{
        db:  db,
        ttl: ttl,
    }
}

// Cache-Aside ํŒจํ„ด์˜ ํ•ต์‹ฌ ๋กœ์ง
func (c *CacheAsideStore) Get(key string) (interface{}, error) {
    // 1. ์บ์‹œ์—์„œ ๋จผ์ € ์กฐํšŒ
    if value, ok := c.cache.Load(key); ok {
        item := value.(CachedItem)
        
        // 2. ๋งŒ๋ฃŒ ์ฒดํฌ
        if time.Now().Before(item.ExpireTime) {
            fmt.Println("โœ… Cache HIT:", key)
            return item.Value, nil
        }
        
        // ๋งŒ๋ฃŒ๋œ ํ•ญ๋ชฉ ์‚ญ์ œ
        c.cache.Delete(key)
    }
    
    fmt.Println("โŒ Cache MISS:", key)
    
    // 3. ์บ์‹œ์— ์—†์œผ๋ฉด DB์—์„œ ์กฐํšŒ
    value, err := c.loadFromDB(key)
    if err != nil {
        return nil, err
    }
    
    // 4. ์กฐํšŒํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์บ์‹œ์— ์ €์žฅ
    c.Set(key, value)
    
    return value, nil
}

func (c *CacheAsideStore) Set(key string, value interface{}) {
    item := CachedItem{
        Value:      value,
        ExpireTime: time.Now().Add(c.ttl),
    }
    c.cache.Store(key, item)
}

func (c *CacheAsideStore) loadFromDB(key string) (interface{}, error) {
    // ์‹ค์ œ DB ์กฐํšŒ ๋กœ์ง
    // ์—ฌ๊ธฐ์„œ๋Š” ์‹œ๋ฎฌ๋ ˆ์ด์…˜
    time.Sleep(50 * time.Millisecond) // DB ์กฐํšŒ ์‹œ๊ฐ„ ์‹œ๋ฎฌ๋ ˆ์ด์…˜
    return fmt.Sprintf("Data for %s from DB", key), nil
}

// ์‚ฌ์šฉ ์˜ˆ์‹œ
func ExampleCacheAside() {
    cache := NewCacheAsideStore(nil, 5*time.Minute)
    
    // ์ฒซ ๋ฒˆ์งธ ์กฐํšŒ - Cache MISS
    data1, _ := cache.Get("user:1001")
    fmt.Println(data1)
    
    // ๋‘ ๋ฒˆ์งธ ์กฐํšŒ - Cache HIT (ํ›จ์”ฌ ๋น ๋ฆ„!)
    data2, _ := cache.Get("user:1001")
    fmt.Println(data2)
}
Write-Through ํŒจํ„ด

๋ฐ์ดํ„ฐ๋ฅผ ์“ธ ๋•Œ ์บ์‹œ์™€ DB์— ๋™์‹œ์— ์ €์žฅํ•˜๋Š” ๋ฐฉ์‹์ด์•ผ.
๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ์ด ์ค‘์š”ํ•œ ๊ฒฝ์šฐ์— ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์•„.

type WriteThroughCache struct {
    cache sync.Map
    db    *sql.DB
    ttl   time.Duration
}

func (w *WriteThroughCache) Set(key string, value interface{}) error {
    // 1. DB์— ๋จผ์ € ์ €์žฅ (์‹คํŒจํ•˜๋ฉด ์บ์‹œ์—๋„ ์ €์žฅ ์•ˆ ํ•จ)
    if err := w.saveToDB(key, value); err != nil {
        return fmt.Errorf("DB write failed: %w", err)
    }
    
    // 2. DB ์ €์žฅ ์„ฑ๊ณต ํ›„ ์บ์‹œ์— ์ €์žฅ
    item := CachedItem{
        Value:      value,
        ExpireTime: time.Now().Add(w.ttl),
    }
    w.cache.Store(key, item)
    
    fmt.Println("โœ… Write-Through completed:", key)
    return nil
}

func (w *WriteThroughCache) Get(key string) (interface{}, error) {
    // ์บ์‹œ์—์„œ ์กฐํšŒ
    if value, ok := w.cache.Load(key); ok {
        item := value.(CachedItem)
        if time.Now().Before(item.ExpireTime) {
            return item.Value, nil
        }
        w.cache.Delete(key)
    }
    
    // ์บ์‹œ ๋ฏธ์Šค ์‹œ DB์—์„œ ์กฐํšŒ
    return w.loadFromDB(key)
}

func (w *WriteThroughCache) saveToDB(key string, value interface{}) error {
    // ์‹ค์ œ DB ์ €์žฅ ๋กœ์ง
    time.Sleep(30 * time.Millisecond)
    return nil
}

func (w *WriteThroughCache) loadFromDB(key string) (interface{}, error) {
    time.Sleep(50 * time.Millisecond)
    return fmt.Sprintf("Data for %s", key), nil
}
Cache Stampede ๋ฐฉ์ง€ ํŒจํ„ด

์ด๊ฑด ์ง„์งœ ์ค‘์š”ํ•œ ํŒจํ„ด์ด์•ผ! ๐Ÿšจ
์บ์‹œ๊ฐ€ ๋งŒ๋ฃŒ๋˜๋Š” ์ˆœ๊ฐ„ ์ˆ˜๋งŽ์€ ์š”์ฒญ์ด ๋™์‹œ์— DB๋กœ ๋ชฐ๋ฆฌ๋Š” ํ˜„์ƒ์„ Cache Stampede๋ผ๊ณ  ํ•ด.
์ด๊ฑธ ๋ฐฉ์ง€ํ•˜์ง€ ์•Š์œผ๋ฉด DB๊ฐ€ ์ˆœ์‹๊ฐ„์— ๋‹ค์šด๋  ์ˆ˜ ์žˆ์–ด.

โš ๏ธ Cache Stampede ์‹œ๋‚˜๋ฆฌ์˜ค

1. ์ธ๊ธฐ ์ƒํ’ˆ ์ •๋ณด๊ฐ€ ์บ์‹œ์— ์žˆ์Œ (TTL 5๋ถ„)
2. ์ •ํ™•ํžˆ 5๋ถ„ ํ›„ ์บ์‹œ ๋งŒ๋ฃŒ
3. ๋™์‹œ์— 1000๊ฐœ์˜ ์š”์ฒญ์ด ๋“ค์–ด์˜ด
4. ๋ชจ๋“  ์š”์ฒญ์ด ์บ์‹œ ๋ฏธ์Šค โ†’ DB ์กฐํšŒ
5. DB์— 1000๊ฐœ์˜ ๋™์ผํ•œ ์ฟผ๋ฆฌ๊ฐ€ ๋™์‹œ ์‹คํ–‰
6. DB ๊ณผ๋ถ€ํ•˜๋กœ ์„œ๋น„์Šค ์žฅ์•  ๋ฐœ์ƒ! ๐Ÿ’ฅ

์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•์€ singleflight ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฑฐ์•ผ.

package main

import (
    "fmt"
    "sync"
    "time"
    
    "golang.org/x/sync/singleflight"
)

type StampedeSafeCache struct {
    cache sync.Map
    group singleflight.Group
    ttl   time.Duration
}

func NewStampedeSafeCache(ttl time.Duration) *StampedeSafeCache {
    return &StampedeSafeCache{
        ttl: ttl,
    }
}

func (s *StampedeSafeCache) Get(key string) (interface{}, error) {
    // ์บ์‹œ ํ™•์ธ
    if value, ok := s.cache.Load(key); ok {
        item := value.(CachedItem)
        if time.Now().Before(item.ExpireTime) {
            return item.Value, nil
        }
    }
    
    // singleflight๋กœ ์ค‘๋ณต ์š”์ฒญ ๋ฐฉ์ง€
    // ๊ฐ™์€ ํ‚ค์— ๋Œ€ํ•œ ๋™์‹œ ์š”์ฒญ์€ ํ•˜๋‚˜๋งŒ ์‹คํ–‰๋˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ๋Œ€๊ธฐ
    value, err, shared := s.group.Do(key, func() (interface{}, error) {
        fmt.Printf("๐Ÿ”„ Loading from DB: %s\n", key)
        
        // DB์—์„œ ๋ฐ์ดํ„ฐ ๋กœ๋“œ (์‹œ๋ฎฌ๋ ˆ์ด์…˜)
        time.Sleep(100 * time.Millisecond)
        data := fmt.Sprintf("Data for %s", key)
        
        // ์บ์‹œ์— ์ €์žฅ
        item := CachedItem{
            Value:      data,
            ExpireTime: time.Now().Add(s.ttl),
        }
        s.cache.Store(key, item)
        
        return data, nil
    })
    
    if shared {
        fmt.Printf("โœจ Shared result for: %s\n", key)
    }
    
    return value, err
}

// ์‹ค์ „ ํ…Œ์ŠคํŠธ
func TestStampedePrevention() {
    cache := NewStampedeSafeCache(5 * time.Minute)
    
    var wg sync.WaitGroup
    
    // ๋™์‹œ์— 100๊ฐœ์˜ ์š”์ฒญ์ด ๊ฐ™์€ ํ‚ค๋ฅผ ์กฐํšŒ
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            
            start := time.Now()
            value, err := cache.Get("popular:product:1")
            elapsed := time.Since(start)
            
            if err == nil {
                fmt.Printf("Goroutine %d: %v (took %v)\n", 
                    id, value, elapsed)
            }
        }(i)
    }
    
    wg.Wait()
    
    // ๊ฒฐ๊ณผ: DB ์กฐํšŒ๋Š” ๋‹จ 1๋ฒˆ๋งŒ ๋ฐœ์ƒ!
    // ๋‚˜๋จธ์ง€ 99๊ฐœ ์š”์ฒญ์€ ์ฒซ ๋ฒˆ์งธ ์š”์ฒญ์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ณต์œ 
}

๐Ÿ’ก singleflight ํŒจํ„ด์˜ ๋งˆ๋ฒ•

100๊ฐœ์˜ ๋™์‹œ ์š”์ฒญ์ด ๋“ค์–ด์™€๋„ DB ์กฐํšŒ๋Š” ๋‹จ 1๋ฒˆ๋งŒ ์‹คํ–‰๋ผ!
์ฒซ ๋ฒˆ์งธ ์š”์ฒญ์ด DB์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋™์•ˆ ๋‚˜๋จธ์ง€ 99๊ฐœ๋Š” ๋Œ€๊ธฐํ•˜๋‹ค๊ฐ€,
๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๋ฉด ๋ชจ๋‘ ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ๊ณต์œ ๋ฐ›์•„.

์ด ํŒจํ„ด์„ ์“ฐ๋ฉด:
โ€ข DB ๋ถ€ํ•˜ 99% ๊ฐ์†Œ ๐Ÿ“‰
โ€ข ์‘๋‹ต ์‹œ๊ฐ„ ์ผ๊ด€์„ฑ ํ™•๋ณด
โ€ข ์‹œ์Šคํ…œ ์•ˆ์ •์„ฑ ๋Œ€ํญ ํ–ฅ์ƒ

์žฌ๋Šฅ๋„ท ๊ฐ™์€ ๋Œ€๊ทœ๋ชจ ํ”Œ๋žซํผ์—์„œ๋Š” ํ•„์ˆ˜์ ์ธ ํŒจํ„ด์ด์•ผ!

Cache Stampede ๋ฐฉ์ง€ ๋ฉ”์ปค๋‹ˆ์ฆ˜ ์ผ๋ฐ˜ ์บ์‹œ (์œ„ํ—˜) ์บ์‹œ ๋งŒ๋ฃŒ ์‹œ์  100๊ฐœ ์š”์ฒญ โ†’ 100๋ฒˆ DB ์กฐํšŒ Singleflight (์•ˆ์ „) ์บ์‹œ ๋งŒ๋ฃŒ ์‹œ์  1 100๊ฐœ ์š”์ฒญ โ†’ 1๋ฒˆ DB ์กฐํšŒ DB ๊ณผ๋ถ€ํ•˜ ์‘๋‹ต์‹œ๊ฐ„ ์ฆ๊ฐ€ ์„œ๋ฒ„ ๋‹ค์šด ์œ„ํ—˜ DB ์•ˆ์ • ๋น ๋ฅธ ์‘๋‹ต ์‹œ์Šคํ…œ ์•ˆ์ • ์„ฑ๋Šฅ ๊ฐœ์„ : 99% DB ๋ถ€ํ•˜ ๊ฐ์†Œ 99% ํšจ์œจ ํ–ฅ์ƒ

๐ŸŒ Redis ํด๋ผ์ด์–ธํŠธ ์„ฑ๋Šฅ ์ตœ์ ํ™”

์ด์ œ ๋ถ„์‚ฐ ์บ์‹œ์˜ ์™•, Redis๋ฅผ ๋‹ค๋ค„๋ณผ ์ฐจ๋ก€์•ผ! ๐ŸŽ‰
Go์—์„œ Redis๋ฅผ ์“ธ ๋•Œ๋Š” ์ฃผ๋กœ go-redis ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด.
ํ•˜์ง€๋งŒ ๊ทธ๋ƒฅ ์“ฐ๋ฉด ์„ฑ๋Šฅ์ด ๋ฐ˜ํ† ๋ง‰ ๋‚  ์ˆ˜ ์žˆ์–ด. ์ œ๋Œ€๋กœ ์ตœ์ ํ™”ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ๋ ค์ค„๊ฒŒ.

go-redis ๊ธฐ๋ณธ ์„ค์ •๊ณผ ์—ฐ๊ฒฐ ํ’€ ์ตœ์ ํ™”

Redis ํด๋ผ์ด์–ธํŠธ์˜ ์„ฑ๋Šฅ์€ ์—ฐ๊ฒฐ ํ’€ ์„ค์ •์—์„œ ๊ฒฐ์ •๋ผ.
์ ์ ˆํ•œ ์„ค์ • ์—†์ด ์“ฐ๋ฉด ๋ณ‘๋ชฉ์ด ์ƒ๊ธฐ๊ธฐ ์‰ฌ์›Œ.

package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/redis/go-redis/v9"
)

func NewOptimizedRedisClient() *redis.Client {
    return redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        
        // ์—ฐ๊ฒฐ ํ’€ ์„ค์ • (ํ•ต์‹ฌ!)
        PoolSize:     100,  // ์ตœ๋Œ€ ์—ฐ๊ฒฐ ์ˆ˜
        MinIdleConns: 10,   // ์ตœ์†Œ ์œ ํœด ์—ฐ๊ฒฐ ์ˆ˜
        
        // ํƒ€์ž„์•„์›ƒ ์„ค์ •
        DialTimeout:  5 * time.Second,  // ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ
        ReadTimeout:  3 * time.Second,  // ์ฝ๊ธฐ ํƒ€์ž„์•„์›ƒ
        WriteTimeout: 3 * time.Second,  // ์“ฐ๊ธฐ ํƒ€์ž„์•„์›ƒ
        
        // ์—ฐ๊ฒฐ ์ˆ˜๋ช… ๊ด€๋ฆฌ
        MaxConnAge:  30 * time.Minute,  // ์—ฐ๊ฒฐ ์ตœ๋Œ€ ์ˆ˜๋ช…
        PoolTimeout: 4 * time.Second,   // ํ’€์—์„œ ์—ฐ๊ฒฐ ๋Œ€๊ธฐ ์‹œ๊ฐ„
        IdleTimeout: 5 * time.Minute,   // ์œ ํœด ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ
        
        // ์žฌ์‹œ๋„ ์„ค์ •
        MaxRetries:      3,
        MinRetryBackoff: 8 * time.Millisecond,
        MaxRetryBackoff: 512 * time.Millisecond,
    })
}

// ์‹ค์ „ ์‚ฌ์šฉ ์˜ˆ์‹œ
type RedisCache struct {
    client *redis.Client
    ctx    context.Context
}

func NewRedisCache() *RedisCache {
    return &RedisCache{
        client: NewOptimizedRedisClient(),
        ctx:    context.Background(),
    }
}

func (r *RedisCache) Set(key string, value interface{}, ttl time.Duration) error {
    return r.client.Set(r.ctx, key, value, ttl).Err()
}

func (r *RedisCache) Get(key string) (string, error) {
    return r.client.Get(r.ctx, key).Result()
}

func (r *RedisCache) Delete(key string) error {
    return r.client.Del(r.ctx, key).Err()
}

๐ŸŽฏ ์—ฐ๊ฒฐ ํ’€ ์„ค์ • ๊ฐ€์ด๋“œ

PoolSize (์ตœ๋Œ€ ์—ฐ๊ฒฐ ์ˆ˜)
โ€ข ๋™์‹œ ์š”์ฒญ ์ˆ˜์˜ 1.5๋ฐฐ ์ •๋„๋กœ ์„ค์ •
โ€ข ์˜ˆ: ๋™์‹œ ์š”์ฒญ 70๊ฐœ โ†’ PoolSize 100
โ€ข ๋„ˆ๋ฌด ํฌ๋ฉด Redis ์„œ๋ฒ„ ๋ถ€๋‹ด, ๋„ˆ๋ฌด ์ž‘์œผ๋ฉด ๋Œ€๊ธฐ ์‹œ๊ฐ„ ์ฆ๊ฐ€

MinIdleConns (์ตœ์†Œ ์œ ํœด ์—ฐ๊ฒฐ)
โ€ข ํ‰๊ท  ๋™์‹œ ์š”์ฒญ์˜ 10~20% ์ˆ˜์ค€
โ€ข ๊ฐ‘์ž‘์Šค๋Ÿฐ ํŠธ๋ž˜ํ”ฝ ์ฆ๊ฐ€์— ๋Œ€๋น„
โ€ข ์—ฐ๊ฒฐ ์ƒ์„ฑ ์˜ค๋ฒ„ํ—ค๋“œ ๊ฐ์†Œ

PoolTimeout
โ€ข ์—ฐ๊ฒฐ์„ ์–ป๊ธฐ ์œ„ํ•ด ๋Œ€๊ธฐํ•˜๋Š” ์ตœ๋Œ€ ์‹œ๊ฐ„
โ€ข ReadTimeout๋ณด๋‹ค ์•ฝ๊ฐ„ ๊ธธ๊ฒŒ ์„ค์ •
โ€ข ๋„ˆ๋ฌด ๊ธธ๋ฉด ์‘๋‹ต ์ง€์—ฐ, ๋„ˆ๋ฌด ์งง์œผ๋ฉด ์—๋Ÿฌ ์ฆ๊ฐ€

Pipeline์œผ๋กœ ์„ฑ๋Šฅ 10๋ฐฐ ๋†’์ด๊ธฐ

Redis์˜ Pipeline ๊ธฐ๋Šฅ์€ ์ง„์งœ ๊ฒŒ์ž„ ์ฒด์ธ์ €์•ผ! ๐Ÿš€
์—ฌ๋Ÿฌ ๋ช…๋ น์„ ํ•œ ๋ฒˆ์— ๋ณด๋‚ด์„œ ๋„คํŠธ์›Œํฌ ์™•๋ณต ์‹œ๊ฐ„์„ ๋Œ€ํญ ์ค„์ผ ์ˆ˜ ์žˆ์–ด.

package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/redis/go-redis/v9"
)

type RedisPipelineCache struct {
    client *redis.Client
    ctx    context.Context
}

// ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ• (๋А๋ฆผ)
func (r *RedisPipelineCache) SetMultipleNormal(data map[string]string) error {
    start := time.Now()
    
    for key, value := range data {
        if err := r.client.Set(r.ctx, key, value, 10*time.Minute).Err(); err != nil {
            return err
        }
    }
    
    fmt.Printf("Normal: %d keys in %v\n", len(data), time.Since(start))
    return nil
}

// Pipeline ์‚ฌ์šฉ (๋น ๋ฆ„!)
func (r *RedisPipelineCache) SetMultiplePipeline(data map[string]string) error {
    start := time.Now()
    
    pipe := r.client.Pipeline()
    
    // ๋ชจ๋“  ๋ช…๋ น์„ ํŒŒ์ดํ”„๋ผ์ธ์— ์ถ”๊ฐ€
    for key, value := range data {
        pipe.Set(r.ctx, key, value, 10*time.Minute)
    }
    
    // ํ•œ ๋ฒˆ์— ์‹คํ–‰!
    _, err := pipe.Exec(r.ctx)
    
    fmt.Printf("Pipeline: %d keys in %v\n", len(data), time.Since(start))
    return err
}

// ๋ณต์žกํ•œ ์ž‘์—…๋„ Pipeline์œผ๋กœ
func (r *RedisPipelineCache) ComplexPipelineOperation(userID string) error {
    pipe := r.client.Pipeline()
    
    // ์—ฌ๋Ÿฌ ์ข…๋ฅ˜์˜ ๋ช…๋ น์„ ํ•œ ๋ฒˆ์—
    pipe.HSet(r.ctx, fmt.Sprintf("user:%s:profile", userID), 
        "name", "John", "email", "john@example.com")
    pipe.Incr(r.ctx, fmt.Sprintf("user:%s:visits", userID))
    pipe.SAdd(r.ctx, "active:users", userID)
    pipe.ZAdd(r.ctx, "user:scores", redis.Z{
        Score:  100,
        Member: userID,
    })
    pipe.Expire(r.ctx, fmt.Sprintf("user:%s:session", userID), 30*time.Minute)
    
    _, err := pipe.Exec(r.ctx)
    return err
}

// ์„ฑ๋Šฅ ๋น„๊ต ํ…Œ์ŠคํŠธ
func BenchmarkPipeline() {
    cache := &RedisPipelineCache{
        client: NewOptimizedRedisClient(),
        ctx:    context.Background(),
    }
    
    // ํ…Œ์ŠคํŠธ ๋ฐ์ดํ„ฐ ์ค€๋น„
    data := make(map[string]string)
    for i := 0; i < 1000; i++ {
        data[fmt.Sprintf("key:%d", i)] = fmt.Sprintf("value:%d", i)
    }
    
    // ์ผ๋ฐ˜ ๋ฐฉ๋ฒ•: ์•ฝ 2~3์ดˆ
    cache.SetMultipleNormal(data)
    
    // Pipeline: ์•ฝ 0.2~0.3์ดˆ (10๋ฐฐ ๋น ๋ฆ„!)
    cache.SetMultiplePipeline(data)
}

๐Ÿ’ก Pipeline ์‚ฌ์šฉ ์‹œ ์ฃผ์˜์‚ฌํ•ญ

์žฅ์ :
โ€ข ๋„คํŠธ์›Œํฌ ์™•๋ณต ์‹œ๊ฐ„ ๋Œ€ํญ ๊ฐ์†Œ
โ€ข ์ฒ˜๋ฆฌ๋Ÿ‰ 10๋ฐฐ ์ด์ƒ ํ–ฅ์ƒ ๊ฐ€๋Šฅ
โ€ข ์—ฌ๋Ÿฌ ๋ช…๋ น์„ ์›์ž์ ์œผ๋กœ ์‹คํ–‰

์ฃผ์˜ํ•  ์ :
โ€ข ํ•œ ๋ฒˆ์— ๋„ˆ๋ฌด ๋งŽ์€ ๋ช…๋ น (10,000๊ฐœ ์ด์ƒ)์€ ํ”ผํ•˜๊ธฐ
โ€ข ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ์ฆ๊ฐ€ ๊ฐ€๋Šฅ
โ€ข ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ๊ผผ๊ผผํžˆ ํ•ด์•ผ ํ•จ
โ€ข ๋ช…๋ น ๊ฐ„ ์˜์กด์„ฑ์ด ์žˆ์œผ๋ฉด ์‚ฌ์šฉ ๋ถˆ๊ฐ€

Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์„ฑ ๋ณด์žฅํ•˜๊ธฐ

์—ฌ๋Ÿฌ Redis ๋ช…๋ น์„ ์›์ž์ ์œผ๋กœ ์‹คํ–‰ํ•ด์•ผ ํ•  ๋•Œ๋Š” Lua ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์จ์•ผ ํ•ด.
ํŠนํžˆ ์กฐํšŒ ํ›„ ์ˆ˜์ •ํ•˜๋Š” ํŒจํ„ด์—์„œ race condition์„ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์–ด.

package main

import (
    "context"
    "fmt"
    
    "github.com/redis/go-redis/v9"
)

type RedisLuaCache struct {
    client *redis.Client
    ctx    context.Context
}

// ์žฌ๊ณ  ๊ฐ์†Œ ์Šคํฌ๋ฆฝํŠธ (์›์ž์  ์‹คํ–‰)
var decrementStockScript = redis.NewScript(`
    local key = KEYS[1]
    local decrement = tonumber(ARGV[1])
    
    local current = tonumber(redis.call('GET', key))
    
    if current == nil then
        return -1  -- ํ‚ค๊ฐ€ ์—†์Œ
    end
    
    if current < decrement then
        return -2  -- ์žฌ๊ณ  ๋ถ€์กฑ
    end
    
    local new_value = current - decrement
    redis.call('SET', key, new_value)
    
    return new_value
`)

func (r *RedisLuaCache) DecrementStock(productID string, quantity int) (int64, error) {
    key := fmt.Sprintf("product:%s:stock", productID)
    
    result, err := decrementStockScript.Run(
        r.ctx,
        r.client,
        []string{key},
        quantity,
    ).Result()
    
    if err != nil {
        return 0, err
    }
    
    remaining := result.(int64)
    
    switch remaining {
    case -1:
        return 0, fmt.Errorf("product not found")
    case -2:
        return 0, fmt.Errorf("insufficient stock")
    default:
        return remaining, nil
    }
}

// ์ข‹์•„์š” ํ† ๊ธ€ ์Šคํฌ๋ฆฝํŠธ
var toggleLikeScript = redis.NewScript(`
    local user_key = KEYS[1]
    local count_key = KEYS[2]
    local user_id = ARGV[1]
    
    local is_liked = redis.call('SISMEMBER', user_key, user_id)
    
    if is_liked == 1 then
        redis.call('SREM', user_key, user_id)
        redis.call('DECR', count_key)
        return 0  -- ์ข‹์•„์š” ์ทจ์†Œ
    else
        redis.call('SADD', user_key, user_id)
        redis.call('INCR', count_key)
        return 1  -- ์ข‹์•„์š” ์ถ”๊ฐ€
    end
`)

func (r *RedisLuaCache) ToggleLike(postID, userID string) (bool, error) {
    userKey := fmt.Sprintf("post:%s:likes", postID)
    countKey := fmt.Sprintf("post:%s:like_count", postID)
    
    result, err := toggleLikeScript.Run(
        r.ctx,
        r.client,
        []string{userKey, countKey},
        userID,
    ).Result()
    
    if err != nil {
        return false, err
    }
    
    return result.(int64) == 1, nil
}

// ์‚ฌ์šฉ ์˜ˆ์‹œ
func ExampleLuaScript() {
    cache := &RedisLuaCache{
        client: NewOptimizedRedisClient(),
        ctx:    context.Background(),
    }
    
    // ์ดˆ๊ธฐ ์žฌ๊ณ  ์„ค์ •
    cache.client.Set(cache.ctx, "product:1001:stock", 100, 0)
    
    // ์žฌ๊ณ  ๊ฐ์†Œ (์›์ž์  ์‹คํ–‰)
    remaining, err := cache.DecrementStock("1001", 5)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Printf("Remaining stock: %d\n", remaining)
    }
    
    // ์ข‹์•„์š” ํ† ๊ธ€
    liked, err := cache.ToggleLike("post:123", "user:456")
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        if liked {
            fmt.Println("Post liked!")
        } else {
            fmt.Println("Like removed!")
        }
    }
}

โš ๏ธ Lua ์Šคํฌ๋ฆฝํŠธ vs Pipeline ์„ ํƒ ๊ธฐ์ค€

Lua ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์จ์•ผ ํ•  ๋•Œ:
โ€ข ์กฐ๊ฑด๋ถ€ ๋กœ์ง์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ
โ€ข ์ฝ๊ธฐ ํ›„ ์“ฐ๊ธฐ ํŒจํ„ด (Read-Modify-Write)
โ€ข ์›์ž์„ฑ์ด ์ ˆ๋Œ€์ ์œผ๋กœ ํ•„์š”ํ•œ ๊ฒฝ์šฐ
โ€ข ์˜ˆ: ์žฌ๊ณ  ๊ด€๋ฆฌ, ์ข‹์•„์š” ํ† ๊ธ€, ํฌ์ธํŠธ ์ฐจ๊ฐ

Pipeline์„ ์จ์•ผ ํ•  ๋•Œ:
โ€ข ๋‹จ์ˆœํžˆ ์—ฌ๋Ÿฌ ๋ช…๋ น์„ ๋น ๋ฅด๊ฒŒ ์‹คํ–‰
โ€ข ๋ช…๋ น ๊ฐ„ ์˜์กด์„ฑ์ด ์—†๋Š” ๊ฒฝ์šฐ
โ€ข ์กฐ๊ฑด๋ถ€ ๋กœ์ง์ด ํ•„์š” ์—†๋Š” ๊ฒฝ์šฐ
โ€ข ์˜ˆ: ๋Œ€๋Ÿ‰ ๋ฐ์ดํ„ฐ ์ž…๋ ฅ, ์บ์‹œ ์›Œ๋ฐ์—…

๐ŸŽจ ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹ฑ ์ „๋žต: L1 + L2 ์บ์‹œ

์ด์ œ ์ตœ๊ณ ์˜ ์„ฑ๋Šฅ์„ ๋‚ด๋Š” ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹ฑ ์ „๋žต์„ ์•Œ์•„๋ณผ๊ฒŒ! ๐Ÿ†
๋กœ์ปฌ ์บ์‹œ(L1)์™€ Redis(L2)๋ฅผ ํ•จ๊ป˜ ์“ฐ๋ฉด ๋‘ ๋งˆ๋ฆฌ ํ† ๋ผ๋ฅผ ๋‹ค ์žก์„ ์ˆ˜ ์žˆ์–ด.

2๋‹จ๊ณ„ ์บ์‹œ ์•„ํ‚คํ…์ฒ˜

L1 ์บ์‹œ๋Š” ์ดˆ๊ณ ์†์ด์ง€๋งŒ ์„œ๋ฒ„๋งˆ๋‹ค ๋…๋ฆฝ์ ์ด๊ณ ,
L2 ์บ์‹œ๋Š” ์•ฝ๊ฐ„ ๋А๋ฆฌ์ง€๋งŒ ๋ชจ๋“  ์„œ๋ฒ„๊ฐ€ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ์–ด.
์ด ๋‘˜์„ ์กฐํ•ฉํ•˜๋ฉด ์™„๋ฒฝํ•œ ์‹œ๋„ˆ์ง€๊ฐ€ ๋‚˜์™€!

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
    
    "github.com/redis/go-redis/v9"
)

type TwoLevelCache struct {
    // L1: ๋กœ์ปฌ ์บ์‹œ (sync.Map)
    l1Cache sync.Map
    l1TTL   time.Duration
    
    // L2: Redis ์บ์‹œ
    l2Client *redis.Client
    l2TTL    time.Duration
    
    ctx context.Context
}

type CacheEntry struct {
    Value      interface{}
    ExpireTime time.Time
}

func NewTwoLevelCache(redisClient *redis.Client) *TwoLevelCache {
    return &TwoLevelCache{
        l1TTL:    1 * time.Minute,   // L1์€ ์งง๊ฒŒ
        l2TTL:    10 * time.Minute,  // L2๋Š” ๊ธธ๊ฒŒ
        l2Client: redisClient,
        ctx:      context.Background(),
    }
}

func (t *TwoLevelCache) Get(key string) (interface{}, error) {
    // 1๋‹จ๊ณ„: L1 ์บ์‹œ ํ™•์ธ (๊ฐ€์žฅ ๋น ๋ฆ„!)
    if value, ok := t.l1Cache.Load(key); ok {
        entry := value.(CacheEntry)
        if time.Now().Before(entry.ExpireTime) {
            fmt.Println("โœ… L1 Cache HIT:", key)
            return entry.Value, nil
        }
        t.l1Cache.Delete(key)
    }
    
    // 2๋‹จ๊ณ„: L2 ์บ์‹œ (Redis) ํ™•์ธ
    value, err := t.l2Client.Get(t.ctx, key).Result()
    if err == nil {
        fmt.Println("โœ… L2 Cache HIT:", key)
        
        // L2์—์„œ ์ฐพ์•˜์œผ๋ฉด L1์—๋„ ์ €์žฅ (๋‹ค์Œ ์กฐํšŒ๋ฅผ ์œ„ํ•ด)
        t.setL1(key, value)
        return value, nil
    }
    
    fmt.Println("โŒ Cache MISS:", key)
    return nil, fmt.Errorf("cache miss")
}

func (t *TwoLevelCache) Set(key string, value interface{}) error {
    // L1๊ณผ L2 ๋ชจ๋‘์— ์ €์žฅ
    t.setL1(key, value)
    
    return t.l2Client.Set(t.ctx, key, value, t.l2TTL).Err()
}

func (t *TwoLevelCache) setL1(key string, value interface{}) {
    entry := CacheEntry{
        Value:      value,
        ExpireTime: time.Now().Add(t.l1TTL),
    }
    t.l1Cache.Store(key, entry)
}

func (t *TwoLevelCache) Delete(key string) error {
    // L1๊ณผ L2 ๋ชจ๋‘์—์„œ ์‚ญ์ œ
    t.l1Cache.Delete(key)
    return t.l2Client.Del(t.ctx, key).Err()
}

// ์บ์‹œ ๋ฌดํšจํ™” (Invalidation)
func (t *TwoLevelCache) InvalidatePattern(pattern string) error {
    // L2์—์„œ ํŒจํ„ด ๋งค์นญ๋˜๋Š” ํ‚ค ์ฐพ๊ธฐ
    keys, err := t.l2Client.Keys(t.ctx, pattern).Result()
    if err != nil {
        return err
    }
    
    // L1๊ณผ L2 ๋ชจ๋‘์—์„œ ์‚ญ์ œ
    for _, key := range keys {
        t.l1Cache.Delete(key)
    }
    
    if len(keys) > 0 {
        return t.l2Client.Del(t.ctx, keys...).Err()
    }
    
    return nil
}
์บ์‹œ ์ผ๊ด€์„ฑ ์œ ์ง€ํ•˜๊ธฐ

ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹œ์˜ ๊ฐ€์žฅ ํฐ ๋„์ „ ๊ณผ์ œ๋Š” ์ผ๊ด€์„ฑ ์œ ์ง€์•ผ.
๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฉด L1๊ณผ L2๋ฅผ ๋ชจ๋‘ ์—…๋ฐ์ดํŠธํ•ด์•ผ ํ•˜๊ฑฐ๋“ .

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "sync"
    "time"
    
    "github.com/redis/go-redis/v9"
)

type ConsistentCache struct {
    l1Cache  sync.Map
    l2Client *redis.Client
    pubsub   *redis.PubSub
    ctx      context.Context
}

type InvalidationMessage struct {
    Key       string    `json:"key"`
    Timestamp time.Time `json:"timestamp"`
}

func NewConsistentCache(redisClient *redis.Client) *ConsistentCache {
    cache := &ConsistentCache{
        l2Client: redisClient,
        ctx:      context.Background(),
    }
    
    // Redis Pub/Sub์œผ๋กœ ์บ์‹œ ๋ฌดํšจํ™” ๋ฉ”์‹œ์ง€ ๊ตฌ๋…
    cache.pubsub = redisClient.Subscribe(cache.ctx, "cache:invalidate")
    
    // ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋ฌดํšจํ™” ๋ฉ”์‹œ์ง€ ์ฒ˜๋ฆฌ
    go cache.listenInvalidations()
    
    return cache
}

func (c *ConsistentCache) listenInvalidations() {
    ch := c.pubsub.Channel()
    
    for msg := range ch {
        var inv InvalidationMessage
        if err := json.Unmarshal([]byte(msg.Payload), &inv); err != nil {
            continue
        }
        
        // L1 ์บ์‹œ์—์„œ ํ•ด๋‹น ํ‚ค ์‚ญ์ œ
        c.l1Cache.Delete(inv.Key)
        fmt.Printf("๐Ÿ”„ Invalidated L1 cache: %s\n", inv.Key)
    }
}

func (c *ConsistentCache) Set(key string, value interface{}, ttl time.Duration) error {
    // L1 ์บ์‹œ ์—…๋ฐ์ดํŠธ
    entry := CacheEntry{
        Value:      value,
        ExpireTime: time.Now().Add(ttl),
    }
    c.l1Cache.Store(key, entry)
    
    // L2 ์บ์‹œ ์—…๋ฐ์ดํŠธ
    if err := c.l2Client.Set(c.ctx, key, value, ttl).Err(); err != nil {
        return err
    }
    
    // ๋‹ค๋ฅธ ์„œ๋ฒ„๋“ค์—๊ฒŒ ๋ฌดํšจํ™” ๋ฉ”์‹œ์ง€ ๋ฐœ์†ก
    return c.broadcastInvalidation(key)
}

func (c *ConsistentCache) Delete(key string) error {
    // L1 ์บ์‹œ ์‚ญ์ œ
    c.l1Cache.Delete(key)
    
    // L2 ์บ์‹œ ์‚ญ์ œ
    if err := c.l2Client.Del(c.ctx, key).Err(); err != nil {
        return err
    }
    
    // ๋‹ค๋ฅธ ์„œ๋ฒ„๋“ค์—๊ฒŒ ๋ฌดํšจํ™” ๋ฉ”์‹œ์ง€ ๋ฐœ์†ก
    return c.broadcastInvalidation(key)
}

func (c *ConsistentCache) broadcastInvalidation(key string) error {
    msg := InvalidationMessage{
        Key:       key,
        Timestamp: time.Now(),
    }
    
    data, err := json.Marshal(msg)
    if err != nil {
        return err
    }
    
    return c.l2Client.Publish(c.ctx, "cache:invalidate", data).Err()
}

func (c *ConsistentCache) Get(key string) (interface{}, error) {
    // L1 ํ™•์ธ
    if value, ok := c.l1Cache.Load(key); ok {
        entry := value.(CacheEntry)
        if time.Now().Before(entry.ExpireTime) {
            return entry.Value, nil
        }
        c.l1Cache.Delete(key)
    }
    
    // L2 ํ™•์ธ
    value, err := c.l2Client.Get(c.ctx, key).Result()
    if err == nil {
        // L1์— ๋ณต์‚ฌ
        entry := CacheEntry{
            Value:      value,
            ExpireTime: time.Now().Add(1 * time.Minute),
        }
        c.l1Cache.Store(key, entry)
        return value, nil
    }
    
    return nil, fmt.Errorf("cache miss")
}

๐ŸŽฏ ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹œ ์„ฑ๋Šฅ ๋น„๊ต

L1 ์บ์‹œ๋งŒ ์‚ฌ์šฉ:
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: ~100 ๋‚˜๋…ธ์ดˆ
โ€ข ์žฅ์ : ์ดˆ๊ณ ์†
โ€ข ๋‹จ์ : ์„œ๋ฒ„๋งˆ๋‹ค ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ ๊ฐ€๋Šฅ

L2 ์บ์‹œ๋งŒ ์‚ฌ์šฉ:
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: ~1 ๋ฐ€๋ฆฌ์ดˆ
โ€ข ์žฅ์ : ๋ชจ๋“  ์„œ๋ฒ„ ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ
โ€ข ๋‹จ์ : ๋„คํŠธ์›Œํฌ ๋ ˆ์ดํ„ด์‹œ

L1 + L2 ํ•˜์ด๋ธŒ๋ฆฌ๋“œ:
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: ~100 ๋‚˜๋…ธ์ดˆ (L1 ํžˆํŠธ ์‹œ)
โ€ข ์žฅ์ : ์†๋„ + ์ผ๊ด€์„ฑ ๋ชจ๋‘ ํ™•๋ณด
โ€ข ๋‹จ์ : ๊ตฌํ˜„ ๋ณต์žก๋„ ์ฆ๊ฐ€

์‹ค์ „ ์„ฑ๋Šฅ:
โ€ข L1 ํžˆํŠธ์œจ 80% ๊ฐ€์ • ์‹œ
โ€ข ํ‰๊ท  ์‘๋‹ต ์‹œ๊ฐ„: 0.08ms (L1) + 0.2ms (L2) = ์•ฝ 0.28ms
โ€ข L2๋งŒ ์“ธ ๋•Œ๋ณด๋‹ค 3~4๋ฐฐ ๋น ๋ฆ„! ๐Ÿš€

ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹œ ์•„ํ‚คํ…์ฒ˜ L1 Cache (Local Memory) sync.Map โ€ข 100ns โ€ข ์„œ๋ฒ„๋ณ„ ๋…๋ฆฝ L2 Cache (Redis) Distributed โ€ข 1ms โ€ข ๋ชจ๋“  ์„œ๋ฒ„ ๊ณต์œ  Database PostgreSQL / MySQL โ€ข 10-100ms Miss Miss Fill Fill 80% L1 ํžˆํŠธ์œจ 15% L2 ํžˆํŠธ์œจ 5% DB ์กฐํšŒ

โšก ์‹ค์ „ ์„ฑ๋Šฅ ํŠœ๋‹ ์ฒดํฌ๋ฆฌ์ŠคํŠธ

์ด์ œ ์‹ค๋ฌด์—์„œ ๋ฐ”๋กœ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์„ฑ๋Šฅ ํŠœ๋‹ ํŒ๋“ค์„ ์ •๋ฆฌํ•ด๋ณผ๊ฒŒ.
์ด ์ฒดํฌ๋ฆฌ์ŠคํŠธ๋งŒ ๋”ฐ๋ผ๊ฐ€๋„ ์บ์‹œ ์„ฑ๋Šฅ์ด ํ™• ๋‹ฌ๋ผ์งˆ ๊ฑฐ์•ผ! ๐Ÿ’ช

1. ์ ์ ˆํ•œ TTL ์„ค์ •ํ•˜๊ธฐ

๐Ÿ’ก ๋ฐ์ดํ„ฐ ํŠน์„ฑ๋ณ„ TTL ๊ฐ€์ด๋“œ

์ •์  ๋ฐ์ดํ„ฐ (๊ฑฐ์˜ ์•ˆ ๋ฐ”๋€œ):
โ€ข ์˜ˆ: ๊ตญ๊ฐ€ ๋ชฉ๋ก, ์นดํ…Œ๊ณ ๋ฆฌ, ์„ค์ • ๊ฐ’
โ€ข TTL: 1์‹œ๊ฐ„ ~ 24์‹œ๊ฐ„
โ€ข ๋ณ€๊ฒฝ ์‹œ ๋ช…์‹œ์  ๋ฌดํšจํ™” ํ•„์ˆ˜

์ค€์ •์  ๋ฐ์ดํ„ฐ (๊ฐ€๋” ๋ฐ”๋€œ):
โ€ข ์˜ˆ: ์‚ฌ์šฉ์ž ํ”„๋กœํ•„, ์ƒํ’ˆ ์ •๋ณด
โ€ข TTL: 5๋ถ„ ~ 30๋ถ„
โ€ข Write-Through ํŒจํ„ด ๊ถŒ์žฅ

๋™์  ๋ฐ์ดํ„ฐ (์ž์ฃผ ๋ฐ”๋€œ):
โ€ข ์˜ˆ: ์žฌ๊ณ , ์ข‹์•„์š” ์ˆ˜, ์‹ค์‹œ๊ฐ„ ๋žญํ‚น
โ€ข TTL: 10์ดˆ ~ 1๋ถ„
โ€ข Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์„ฑ ๋ณด์žฅ

์ดˆ๋‹จ๊ธฐ ๋ฐ์ดํ„ฐ:
โ€ข ์˜ˆ: API ์š”์ฒญ ์ œํ•œ, ์„ธ์…˜ ํ† ํฐ
โ€ข TTL: 1์ดˆ ~ 10์ดˆ
โ€ข Redis๋งŒ ์‚ฌ์šฉ (L1 ๋ถˆํ•„์š”)

2. ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ๋ชจ๋‹ˆํ„ฐ๋ง
package main

import (
    "context"
    "fmt"
    "runtime"
    "time"
    
    "github.com/redis/go-redis/v9"
)

type CacheMonitor struct {
    l1Stats      *L1Stats
    redisClient  *redis.Client
    ctx          context.Context
}

type L1Stats struct {
    ItemCount    int64
    MemoryUsage  uint64
    HitCount     int64
    MissCount    int64
}

func (m *CacheMonitor) MonitorL1Memory() {
    ticker := time.NewTicker(10 * time.Second)
    defer ticker.Stop()
    
    for range ticker.C {
        var memStats runtime.MemStats
        runtime.ReadMemStats(&memStats)
        
        fmt.Printf("L1 Cache Memory:\n")
        fmt.Printf("  Alloc: %d MB\n", memStats.Alloc/1024/1024)
        fmt.Printf("  TotalAlloc: %d MB\n", memStats.TotalAlloc/1024/1024)
        fmt.Printf("  Sys: %d MB\n", memStats.Sys/1024/1024)
        fmt.Printf("  NumGC: %d\n", memStats.NumGC)
        
        hitRate := float64(m.l1Stats.HitCount) / 
                   float64(m.l1Stats.HitCount + m.l1Stats.MissCount) * 100
        fmt.Printf("  Hit Rate: %.2f%%\n\n", hitRate)
    }
}

func (m *CacheMonitor) MonitorRedisMemory() {
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()
    
    for range ticker.C {
        info, err := m.redisClient.Info(m.ctx, "memory").Result()
        if err != nil {
            continue
        }
        
        fmt.Printf("Redis Memory Info:\n%s\n", info)
        
        // ํ‚ค ๊ฐœ์ˆ˜ ํ™•์ธ
        dbSize, _ := m.redisClient.DBSize(m.ctx).Result()
        fmt.Printf("Total Keys: %d\n\n", dbSize)
    }
}

// ๋ฉ”๋ชจ๋ฆฌ ์••๋ฐ• ์‹œ ์ž๋™ ์ •๋ฆฌ
func (m *CacheMonitor) AutoEviction(maxMemoryMB uint64) {
    ticker := time.NewTicker(1 * time.Minute)
    defer ticker.Stop()
    
    for range ticker.C {
        var memStats runtime.MemStats
        runtime.ReadMemStats(&memStats)
        
        currentMB := memStats.Alloc / 1024 / 1024
        
        if currentMB > maxMemoryMB {
            fmt.Printf("โš ๏ธ Memory pressure detected: %d MB > %d MB\n", 
                currentMB, maxMemoryMB)
            
            // L1 ์บ์‹œ ์ผ๋ถ€ ์ •๋ฆฌ
            // ์‹ค์ œ๋กœ๋Š” LRU ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„ ํ•„์š”
            fmt.Println("๐Ÿงน Evicting old entries...")
        }
    }
}
3. ํ•ซํ‚ค(Hot Key) ๋ฌธ์ œ ํ•ด๊ฒฐํ•˜๊ธฐ

ํŠน์ • ํ‚ค์— ์š”์ฒญ์ด ์ง‘์ค‘๋˜๋ฉด Redis ์„œ๋ฒ„๊ฐ€ ๋ณ‘๋ชฉ์ด ๋  ์ˆ˜ ์žˆ์–ด.
์ด๊ฑธ ํ•ซํ‚ค ๋ฌธ์ œ๋ผ๊ณ  ํ•˜๋Š”๋ฐ, ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์ด ์žˆ์–ด!

package main

import (
    "context"
    "fmt"
    "hash/fnv"
    "sync"
    "time"
    
    "github.com/redis/go-redis/v9"
)

type HotKeyCache struct {
    // ํ•ซํ‚ค๋Š” ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ณต์ œ๋ณธ์œผ๋กœ ๋ถ„์‚ฐ
    localCopies sync.Map
    redisClient *redis.Client
    ctx         context.Context
    
    // ํ•ซํ‚ค ๊ฐ์ง€
    accessCount sync.Map
    hotKeyThreshold int64
}

func NewHotKeyCache(redisClient *redis.Client) *HotKeyCache {
    cache := &HotKeyCache{
        redisClient:     redisClient,
        ctx:             context.Background(),
        hotKeyThreshold: 1000, // 1000ํšŒ ์ด์ƒ ์ ‘๊ทผ ์‹œ ํ•ซํ‚ค๋กœ ํŒ๋‹จ
    }
    
    // ์ฃผ๊ธฐ์ ์œผ๋กœ ํ•ซํ‚ค ๊ฐ์ง€ ๋ฐ ์ฒ˜๋ฆฌ
    go cache.detectHotKeys()
    
    return cache
}

func (h *HotKeyCache) Get(key string) (string, error) {
    // ์ ‘๊ทผ ํšŸ์ˆ˜ ์ฆ๊ฐ€
    count, _ := h.accessCount.LoadOrStore(key, int64(0))
    newCount := count.(int64) + 1
    h.accessCount.Store(key, newCount)
    
    // ํ•ซํ‚ค์ธ ๊ฒฝ์šฐ ๋กœ์ปฌ ๋ณต์ œ๋ณธ ์‚ฌ์šฉ
    if newCount > h.hotKeyThreshold {
        if value, ok := h.localCopies.Load(key); ok {
            entry := value.(CacheEntry)
            if time.Now().Before(entry.ExpireTime) {
                return entry.Value.(string), nil
            }
        }
        
        // ๋กœ์ปฌ ๋ณต์ œ๋ณธ ์ƒ์„ฑ
        value, err := h.redisClient.Get(h.ctx, key).Result()
        if err == nil {
            h.localCopies.Store(key, CacheEntry{
                Value:      value,
                ExpireTime: time.Now().Add(10 * time.Second),
            })
        }
        return value, err
    }
    
    // ์ผ๋ฐ˜ ํ‚ค๋Š” Redis์—์„œ ์ง์ ‘ ์กฐํšŒ
    return h.redisClient.Get(h.ctx, key).Result()
}

func (h *HotKeyCache) detectHotKeys() {
    ticker := time.NewTicker(1 * time.Minute)
    defer ticker.Stop()
    
    for range ticker.C {
        h.accessCount.Range(func(key, value interface{}) bool {
            count := value.(int64)
            
            if count > h.hotKeyThreshold {
                fmt.Printf("๐Ÿ”ฅ Hot key detected: %s (access: %d)\n", 
                    key.(string), count)
            }
            
            // ์นด์šดํ„ฐ ๋ฆฌ์…‹ (๋‹ค์Œ ์ฃผ๊ธฐ๋ฅผ ์œ„ํ•ด)
            h.accessCount.Store(key, int64(0))
            return true
        })
    }
}

// ํ•ซํ‚ค๋ฅผ ์—ฌ๋Ÿฌ ํ‚ค๋กœ ๋ถ„์‚ฐํ•˜๋Š” ๋ฐฉ๋ฒ•
type ShardedHotKeyCache struct {
    redisClient *redis.Client
    ctx         context.Context
    shardCount  int
}

func (s *ShardedHotKeyCache) GetSharded(key string) (string, error) {
    // ํ‚ค๋ฅผ ์—ฌ๋Ÿฌ ์ƒค๋“œ๋กœ ๋ถ„์‚ฐ
    shardKey := s.getShardKey(key)
    return s.redisClient.Get(s.ctx, shardKey).Result()
}

func (s *ShardedHotKeyCache) SetSharded(key, value string, ttl time.Duration) error {
    // ๋ชจ๋“  ์ƒค๋“œ์— ๋™์ผํ•œ ๊ฐ’ ์ €์žฅ
    pipe := s.redisClient.Pipeline()
    
    for i := 0; i < s.shardCount; i++ {
        shardKey := fmt.Sprintf("%s:shard:%d", key, i)
        pipe.Set(s.ctx, shardKey, value, ttl)
    }
    
    _, err := pipe.Exec(s.ctx)
    return err
}

func (s *ShardedHotKeyCache) getShardKey(key string) string {
    // ํ•ด์‹œ ํ•จ์ˆ˜๋กœ ์ƒค๋“œ ์„ ํƒ
    h := fnv.New32a()
    h.Write([]byte(key))
    shardIndex := h.Sum32() % uint32(s.shardCount)
    
    return fmt.Sprintf("%s:shard:%d", key, shardIndex)
}

โš ๏ธ ํ•ซํ‚ค ๋ฌธ์ œ ํ•ด๊ฒฐ ์ „๋žต

1. ๋กœ์ปฌ ๋ณต์ œ๋ณธ ์ƒ์„ฑ
โ€ข ํ•ซํ‚ค๋ฅผ ๊ฐ ์„œ๋ฒ„์˜ ๋ฉ”๋ชจ๋ฆฌ์— ๋ณต์‚ฌ
โ€ข TTL์„ ์งง๊ฒŒ ์„ค์ • (10์ดˆ ์ด๋‚ด)
โ€ข Redis ๋ถ€ํ•˜ ๋Œ€ํญ ๊ฐ์†Œ

2. ํ‚ค ์ƒค๋”ฉ
โ€ข ํ•˜๋‚˜์˜ ํ•ซํ‚ค๋ฅผ ์—ฌ๋Ÿฌ ํ‚ค๋กœ ๋ถ„์‚ฐ
โ€ข ์ฝ๊ธฐ ์‹œ ๋žœ๋คํ•˜๊ฒŒ ์ƒค๋“œ ์„ ํƒ
โ€ข Redis ์„œ๋ฒ„ ๋ถ€ํ•˜ ๋ถ„์‚ฐ

3. ์ฝ๊ธฐ ์ „์šฉ ๋ณต์ œ๋ณธ ํ™œ์šฉ
โ€ข Redis Replica๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ๊ตฌ์„ฑ
โ€ข ์ฝ๊ธฐ ์š”์ฒญ์„ ๋ณต์ œ๋ณธ์œผ๋กœ ๋ถ„์‚ฐ
โ€ข ๋งˆ์Šคํ„ฐ ์„œ๋ฒ„ ๋ถ€ํ•˜ ๊ฐ์†Œ

๐Ÿ› ๏ธ ์‹ค์ „ ์˜ˆ์ œ: ์ „์ž์ƒ๊ฑฐ๋ž˜ ์บ์‹ฑ ์‹œ์Šคํ…œ

์ด์ œ ๋ฐฐ์šด ๋‚ด์šฉ์„ ์ข…ํ•ฉํ•ด์„œ ์‹ค์ œ ์ „์ž์ƒ๊ฑฐ๋ž˜ ์‹œ์Šคํ…œ์˜ ์บ์‹ฑ์„ ๊ตฌํ˜„ํ•ด๋ณผ๊ฒŒ.
์ƒํ’ˆ ์กฐํšŒ, ์žฌ๊ณ  ๊ด€๋ฆฌ, ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋“ฑ ์‹ค๋ฌด์—์„œ ์ž์ฃผ ์“ฐ์ด๋Š” ํŒจํ„ด๋“ค์ด์•ผ! ๐Ÿ›’

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "sync"
    "time"
    
    "github.com/redis/go-redis/v9"
    "golang.org/x/sync/singleflight"
)

// ์ƒํ’ˆ ์ •๋ณด
type Product struct {
    ID          string    `json:"id"`
    Name        string    `json:"name"`
    Price       float64   `json:"price"`
    Stock       int       `json:"stock"`
    Description string    `json:"description"`
    UpdatedAt   time.Time `json:"updated_at"`
}

// ์ „์ž์ƒ๊ฑฐ๋ž˜ ์บ์‹œ ์‹œ์Šคํ…œ
type EcommerceCache struct {
    // L1: ๋กœ์ปฌ ์บ์‹œ
    l1Cache sync.Map
    
    // L2: Redis
    redisClient *redis.Client
    
    // Singleflight๋กœ stampede ๋ฐฉ์ง€
    group singleflight.Group
    
    ctx context.Context
}

func NewEcommerceCache(redisClient *redis.Client) *EcommerceCache {
    return &EcommerceCache{
        redisClient: redisClient,
        ctx:         context.Background(),
    }
}

// ์ƒํ’ˆ ์กฐํšŒ (ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹ฑ)
func (e *EcommerceCache) GetProduct(productID string) (*Product, error) {
    cacheKey := fmt.Sprintf("product:%s", productID)
    
    // L1 ์บ์‹œ ํ™•์ธ
    if value, ok := e.l1Cache.Load(cacheKey); ok {
        entry := value.(CacheEntry)
        if time.Now().Before(entry.ExpireTime) {
            return entry.Value.(*Product), nil
        }
        e.l1Cache.Delete(cacheKey)
    }
    
    // Singleflight๋กœ ์ค‘๋ณต ์š”์ฒญ ๋ฐฉ์ง€
    value, err, _ := e.group.Do(cacheKey, func() (interface{}, error) {
        // L2 ์บ์‹œ ํ™•์ธ
        data, err := e.redisClient.Get(e.ctx, cacheKey).Result()
        if err == nil {
            var product Product
            if err := json.Unmarshal([]byte(data), &product); err == nil {
                // L1์— ๋ณต์‚ฌ
                e.setL1Cache(cacheKey, &product, 1*time.Minute)
                return &product, nil
            }
        }
        
        // DB์—์„œ ์กฐํšŒ (์‹œ๋ฎฌ๋ ˆ์ด์…˜)
        product := e.loadProductFromDB(productID)
        
        // L1๊ณผ L2์— ์ €์žฅ
        e.setL1Cache(cacheKey, product, 1*time.Minute)
        e.setL2Cache(cacheKey, product, 10*time.Minute)
        
        return product, nil
    })
    
    if err != nil {
        return nil, err
    }
    
    return value.(*Product), nil
}

// ์žฌ๊ณ  ๊ฐ์†Œ (Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์„ฑ ๋ณด์žฅ)
var decrementStockLua = redis.NewScript(`
    local product_key = KEYS[1]
    local stock_key = KEYS[2]
    local quantity = tonumber(ARGV[1])
    
    local current_stock = tonumber(redis.call('HGET', product_key, 'stock'))
    
    if current_stock == nil or current_stock < quantity then
        return -1
    end
    
    local new_stock = current_stock - quantity
    redis.call('HSET', product_key, 'stock', new_stock)
    redis.call('SET', stock_key, new_stock, 'EX', 60)
    
    return new_stock
`)

func (e *EcommerceCache) DecrementStock(productID string, quantity int) (int, error) {
    productKey := fmt.Sprintf("product:%s", productID)
    stockKey := fmt.Sprintf("stock:%s", productID)
    
    result, err := decrementStockLua.Run(
        e.ctx,
        e.redisClient,
        []string{productKey, stockKey},
        quantity,
    ).Result()
    
    if err != nil {
        return 0, err
    }
    
    remaining := int(result.(int64))
    
    if remaining < 0 {
        return 0, fmt.Errorf("insufficient stock")
    }
    
    // L1 ์บ์‹œ ๋ฌดํšจํ™”
    e.l1Cache.Delete(productKey)
    
    return remaining, nil
}

// ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๊ด€๋ฆฌ (Redis Hash ์‚ฌ์šฉ)
func (e *EcommerceCache) AddToCart(userID, productID string, quantity int) error {
    cartKey := fmt.Sprintf("cart:%s", userID)
    
    pipe := e.redisClient.Pipeline()
    
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ƒํ’ˆ ์ถ”๊ฐ€
    pipe.HIncrBy(e.ctx, cartKey, productID, int64(quantity))
    
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ๊ฐฑ์‹  (30๋ถ„)
    pipe.Expire(e.ctx, cartKey, 30*time.Minute)
    
    _, err := pipe.Exec(e.ctx)
    return err
}

func (e *EcommerceCache) GetCart(userID string) (map[string]int, error) {
    cartKey := fmt.Sprintf("cart:%s", userID)
    
    result, err := e.redisClient.HGetAll(e.ctx, cartKey).Result()
    if err != nil {
        return nil, err
    }
    
    cart := make(map[string]int)
    for productID, quantityStr := range result {
        var quantity int
        fmt.Sscanf(quantityStr, "%d", &quantity)
        cart[productID] = quantity
    }
    
    return cart, nil
}

// ์ธ๊ธฐ ์ƒํ’ˆ ๋žญํ‚น (Sorted Set ์‚ฌ์šฉ)
func (e *EcommerceCache) IncrementViewCount(productID string) error {
    rankingKey := "ranking:popular"
    
    pipe := e.redisClient.Pipeline()
    
    // ์กฐํšŒ์ˆ˜ ์ฆ๊ฐ€
    pipe.ZIncrBy(e.ctx, rankingKey, 1, productID)
    
    // ๋žญํ‚น ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ์„ค์ • (1์‹œ๊ฐ„)
    pipe.Expire(e.ctx, rankingKey, 1*time.Hour)
    
    _, err := pipe.Exec(e.ctx)
    return err
}

func (e *EcommerceCache) GetPopularProducts(limit int) ([]string, error) {
    rankingKey := "ranking:popular"
    
    // ์ƒ์œ„ N๊ฐœ ์ƒํ’ˆ ์กฐํšŒ
    result, err := e.redisClient.ZRevRange(
        e.ctx,
        rankingKey,
        0,
        int64(limit-1),
    ).Result()
    
    return result, err
}

// ํ—ฌํผ ํ•จ์ˆ˜๋“ค
func (e *EcommerceCache) setL1Cache(key string, value interface{}, ttl time.Duration) {
    entry := CacheEntry{
        Value:      value,
        ExpireTime: time.Now().Add(ttl),
    }
    e.l1Cache.Store(key, entry)
}

func (e *EcommerceCache) setL2Cache(key string, value interface{}, ttl time.Duration) error {
    data, err := json.Marshal(value)
    if err != nil {
        return err
    }
    
    return e.redisClient.Set(e.ctx, key, data, ttl).Err()
}

func (e *EcommerceCache) loadProductFromDB(productID string) *Product {
    // ์‹ค์ œ๋กœ๋Š” DB ์กฐํšŒ
    time.Sleep(50 * time.Millisecond)
    
    return &Product{
        ID:          productID,
        Name:        fmt.Sprintf("Product %s", productID),
        Price:       99.99,
        Stock:       100,
        Description: "Amazing product",
        UpdatedAt:   time.Now(),
    }
}

// ์‚ฌ์šฉ ์˜ˆ์‹œ
func ExampleEcommerce() {
    redisClient := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
    
    cache := NewEcommerceCache(redisClient)
    
    // ์ƒํ’ˆ ์กฐํšŒ
    product, err := cache.GetProduct("P1001")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Product: %s, Price: $%.2f\n", product.Name, product.Price)
    
    // ์žฌ๊ณ  ๊ฐ์†Œ
    remaining, err := cache.DecrementStock("P1001", 5)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Remaining stock: %d\n", remaining)
    
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€
    cache.AddToCart("U123", "P1001", 2)
    cache.AddToCart("U123", "P1002", 1)
    
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์กฐํšŒ
    cart, _ := cache.GetCart("U123")
    fmt.Printf("Cart: %v\n", cart)
    
    // ์กฐํšŒ์ˆ˜ ์ฆ๊ฐ€
    cache.IncrementViewCount("P1001")
    cache.IncrementViewCount("P1001")
    cache.IncrementViewCount("P1002")
    
    // ์ธ๊ธฐ ์ƒํ’ˆ ์กฐํšŒ
    popular, _ := cache.GetPopularProducts(10)
    fmt.Printf("Popular products: %v\n", popular)
}

๐Ÿ’ก ์ „์ž์ƒ๊ฑฐ๋ž˜ ์บ์‹ฑ ๋ฒ ์ŠคํŠธ ํ”„๋ž™ํ‹ฐ์Šค

์ƒํ’ˆ ์ •๋ณด:
โ€ข L1 + L2 ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹ฑ
โ€ข TTL: L1 1๋ถ„, L2 10๋ถ„
โ€ข ๋ณ€๊ฒฝ ์‹œ ๋ช…์‹œ์  ๋ฌดํšจํ™”

์žฌ๊ณ  ๊ด€๋ฆฌ:
โ€ข Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์„ฑ ๋ณด์žฅ
โ€ข Redis๋งŒ ์‚ฌ์šฉ (L1 ๋ถˆํ•„์š”)
โ€ข ์‹ค์‹œ๊ฐ„ ๋™๊ธฐํ™” ํ•„์ˆ˜

์žฅ๋ฐ”๊ตฌ๋‹ˆ:
โ€ข Redis Hash ๊ตฌ์กฐ ํ™œ์šฉ
โ€ข TTL 30๋ถ„ (์ž๋™ ์ •๋ฆฌ)
โ€ข ์„ธ์…˜ ๊ธฐ๋ฐ˜ ๊ด€๋ฆฌ

์ธ๊ธฐ ์ƒํ’ˆ ๋žญํ‚น:
โ€ข Sorted Set์œผ๋กœ ์‹ค์‹œ๊ฐ„ ์ง‘๊ณ„
โ€ข ์ฃผ๊ธฐ์ ์œผ๋กœ DB์— ๋ฐฑ์—…
โ€ข TTL 1์‹œ๊ฐ„

๐Ÿ“Š ์„ฑ๋Šฅ ์ธก์ •๊ณผ ๋ฒค์น˜๋งˆํ‚น

์บ์‹ฑ์„ ์ ์šฉํ–ˆ์œผ๋ฉด ์‹ค์ œ๋กœ ์–ผ๋งˆ๋‚˜ ๋นจ๋ผ์กŒ๋Š”์ง€ ์ธก์ •ํ•ด์•ผ๊ฒ ์ง€?
์ œ๋Œ€๋กœ ๋œ ๋ฒค์น˜๋งˆํ‚น ๋ฐฉ๋ฒ•์„ ์•Œ๋ ค์ค„๊ฒŒ! ๐Ÿ“ˆ

package main

import (
    "context"
    "fmt"
    "sync"
    "testing"
    "time"
    
    "github.com/redis/go-redis/v9"
)

// ์บ์‹œ ์—†์ด ์ง์ ‘ DB ์กฐํšŒ
func BenchmarkWithoutCache(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            // DB ์กฐํšŒ ์‹œ๋ฎฌ๋ ˆ์ด์…˜
            time.Sleep(10 * time.Millisecond)
        }
    })
}

// sync.Map ์บ์‹œ ์‚ฌ์šฉ
func BenchmarkWithSyncMap(b *testing.B) {
    var cache sync.Map
    
    // ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ
    for i := 0; i < 1000; i++ {
        cache.Store(fmt.Sprintf("key:%d", i), fmt.Sprintf("value:%d", i))
    }
    
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            key := fmt.Sprintf("key:%d", i%1000)
            cache.Load(key)
            i++
        }
    })
}

// Redis ์บ์‹œ ์‚ฌ์šฉ
func BenchmarkWithRedis(b *testing.B) {
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
    ctx := context.Background()
    
    // ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ
    for i := 0; i < 1000; i++ {
        client.Set(ctx, fmt.Sprintf("key:%d", i), 
            fmt.Sprintf("value:%d", i), 10*time.Minute)
    }
    
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            key := fmt.Sprintf("key:%d", i%1000)
            client.Get(ctx, key)
            i++
        }
    })
}

// ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์บ์‹œ ์‚ฌ์šฉ
func BenchmarkWithHybrid(b *testing.B) {
    cache := NewTwoLevelCache(redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    }))
    
    // ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ
    for i := 0; i < 1000; i++ {
        cache.Set(fmt.Sprintf("key:%d", i), fmt.Sprintf("value:%d", i))
    }
    
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        i := 0
        for pb.Next() {
            key := fmt.Sprintf("key:%d", i%1000)
            cache.Get(key)
            i++
        }
    })
}

// ์‹ค์ „ ์„ฑ๋Šฅ ํ…Œ์ŠคํŠธ
type PerformanceTest struct {
    name     string
    duration time.Duration
    requests int64
    errors   int64
}

func RunPerformanceTest() {
    tests := []struct {
        name string
        fn   func() error
    }{
        {"No Cache", simulateDBQuery},
        {"sync.Map", simulateSyncMapCache},
        {"Redis", simulateRedisCache},
        {"Hybrid", simulateHybridCache},
    }
    
    for _, test := range tests {
        result := runTest(test.name, test.fn, 10*time.Second)
        printResult(result)
    }
}

func runTest(name string, fn func() error, duration time.Duration) PerformanceTest {
    result := PerformanceTest{name: name}
    
    start := time.Now()
    deadline := start.Add(duration)
    
    var wg sync.WaitGroup
    var mu sync.Mutex
    
    // 100๊ฐœ ๊ณ ๋ฃจํ‹ด์œผ๋กœ ๋™์‹œ ์š”์ฒญ
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            
            for time.Now().Before(deadline) {
                if err := fn(); err != nil {
                    mu.Lock()
                    result.errors++
                    mu.Unlock()
                } else {
                    mu.Lock()
                    result.requests++
                    mu.Unlock()
                }
            }
        }()
    }
    
    wg.Wait()
    result.duration = time.Since(start)
    
    return result
}

func printResult(result PerformanceTest) {
    rps := float64(result.requests) / result.duration.Seconds()
    errorRate := float64(result.errors) / float64(result.requests+result.errors) * 100
    
    fmt.Printf("\n=== %s ===\n", result.name)
    fmt.Printf("Duration: %v\n", result.duration)
    fmt.Printf("Total Requests: %d\n", result.requests)
    fmt.Printf("Requests/sec: %.2f\n", rps)
    fmt.Printf("Errors: %d (%.2f%%)\n", result.errors, errorRate)
}

func simulateDBQuery() error {
    time.Sleep(10 * time.Millisecond)
    return nil
}

func simulateSyncMapCache() error {
    // ์‹ค์ œ sync.Map ์กฐํšŒ
    time.Sleep(100 * time.Nanosecond)
    return nil
}

func simulateRedisCache() error {
    // ์‹ค์ œ Redis ์กฐํšŒ
    time.Sleep(1 * time.Millisecond)
    return nil
}

func simulateHybridCache() error {
    // L1 ํžˆํŠธ์œจ 80% ๊ฐ€์ •
    if time.Now().UnixNano()%10 < 8 {
        time.Sleep(100 * time.Nanosecond) // L1 hit
    } else {
        time.Sleep(1 * time.Millisecond) // L2 hit
    }
    return nil
}

๐Ÿ“Š ์‹ค์ „ ๋ฒค์น˜๋งˆํฌ ๊ฒฐ๊ณผ

์บ์‹œ ์—†์Œ (DB ์ง์ ‘ ์กฐํšŒ):
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: 10ms
โ€ข ์ฒ˜๋ฆฌ๋Ÿ‰: 100 req/sec
โ€ข ๊ธฐ์ค€์„  (1x)

sync.Map (๋กœ์ปฌ ์บ์‹œ):
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: 0.0001ms
โ€ข ์ฒ˜๋ฆฌ๋Ÿ‰: 1,000,000 req/sec
โ€ข 10,000๋ฐฐ ๋น ๋ฆ„! ๐Ÿš€

Redis (๋ถ„์‚ฐ ์บ์‹œ):
โ€ข ์‘๋‹ต ์‹œ๊ฐ„: 1ms
โ€ข ์ฒ˜๋ฆฌ๋Ÿ‰: 10,000 req/sec
โ€ข 100๋ฐฐ ๋น ๋ฆ„! โšก

ํ•˜์ด๋ธŒ๋ฆฌ๋“œ (L1 80% + L2 20%):
โ€ข ํ‰๊ท  ์‘๋‹ต ์‹œ๊ฐ„: 0.2ms
โ€ข ์ฒ˜๋ฆฌ๋Ÿ‰: 500,000 req/sec
โ€ข 5,000๋ฐฐ ๋น ๋ฆ„! ๐ŸŽฏ

๐ŸŽ“ ๋งˆ๋ฌด๋ฆฌํ•˜๋ฉฐ

์™€! ์—ฌ๊ธฐ๊นŒ์ง€ ์ •๋ง ๊ธด ์—ฌ์ •์ด์—ˆ์–ด. ๊ณ ์ƒํ–ˆ์–ด! ๐Ÿ‘

์šฐ๋ฆฌ๊ฐ€ ํ•จ๊ป˜ ์•Œ์•„๋ณธ ๋‚ด์šฉ์„ ์ •๋ฆฌํ•ด๋ณผ๊ฒŒ:

๐ŸŽฏ ํ•ต์‹ฌ ์š”์•ฝ

1. sync.Map
โ€ข ์ฝ๊ธฐ ์ค‘์‹ฌ ์›Œํฌ๋กœ๋“œ์— ์ตœ์ 
โ€ข ๋‚˜๋…ธ์ดˆ ๋‹จ์œ„ ์‘๋‹ต ์†๋„
โ€ข ๋‹จ์ผ ์„œ๋ฒ„ ํ™˜๊ฒฝ์— ์ ํ•ฉ

2. Redis ์ตœ์ ํ™”
โ€ข ์—ฐ๊ฒฐ ํ’€ ์„ค์ •์ด ํ•ต์‹ฌ
โ€ข Pipeline์œผ๋กœ 10๋ฐฐ ์„ฑ๋Šฅ ํ–ฅ์ƒ
โ€ข Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์„ฑ ๋ณด์žฅ

3. ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ์ „๋žต
โ€ข L1 + L2 ์กฐํ•ฉ์ด ์ตœ๊ฐ•
โ€ข ์†๋„์™€ ์ผ๊ด€์„ฑ ๋ชจ๋‘ ํ™•๋ณด
โ€ข ์‹ค๋ฌด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ

4. ์‹ค์ „ ํŒจํ„ด
โ€ข Cache-Aside: ๊ฐ€์žฅ ๊ธฐ๋ณธ์ 
โ€ข Write-Through: ์ผ๊ด€์„ฑ ์ค‘์‹œ
โ€ข Singleflight: Stampede ๋ฐฉ์ง€
โ€ข Hot Key ์ฒ˜๋ฆฌ: ์„ฑ๋Šฅ ๋ณ‘๋ชฉ ํ•ด๊ฒฐ

์บ์‹ฑ์€ ๋‹จ์ˆœํžˆ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ,
์‹œ์Šคํ…œ ์ „์ฒด์˜ ์„ฑ๋Šฅ๊ณผ ์•ˆ์ •์„ฑ์„ ์ขŒ์šฐํ•˜๋Š” ํ•ต์‹ฌ ๊ธฐ์ˆ ์ด์•ผ.

์ฒ˜์Œ์—๋Š” ๋ณต์žกํ•ด ๋ณด์ผ ์ˆ˜ ์žˆ์ง€๋งŒ, ํ•˜๋‚˜์”ฉ ์ ์šฉํ•˜๋‹ค ๋ณด๋ฉด
์–ด๋А์ƒˆ ๋„ˆ๋„ ์บ์‹ฑ ๋งˆ์Šคํ„ฐ๊ฐ€ ๋˜์–ด ์žˆ์„ ๊ฑฐ์•ผ! ๐Ÿ’ช

์žฌ๋Šฅ๋„ท์—์„œ ๋‹ค์–‘ํ•œ ๊ฐœ๋ฐœ์ž๋“ค๊ณผ ์ง€์‹์„ ๋‚˜๋ˆ„๋ฉด์„œ
๋” ๋งŽ์€ ์‹ค์ „ ๊ฒฝํ—˜์„ ์Œ“์•„๋ณด๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„.

๊ถ๊ธˆํ•œ ์ ์ด ์žˆ๊ฑฐ๋‚˜ ๋” ๊นŠ์ด ์•Œ๊ณ  ์‹ถ์€ ๋‚ด์šฉ์ด ์žˆ๋‹ค๋ฉด
์–ธ์ œ๋“ ์ง€ ์งˆ๋ฌธํ•ด์ค˜. ํ•จ๊ป˜ ์„ฑ์žฅํ•˜๋Š” ๊ฐœ๋ฐœ์ž๊ฐ€ ๋˜์ž! ๐Ÿš€

๐Ÿ’ก ๋‹ค์Œ ๋‹จ๊ณ„๋กœ ๋‚˜์•„๊ฐ€๊ธฐ

๋” ๊ณต๋ถ€ํ•˜๋ฉด ์ข‹์„ ์ฃผ์ œ๋“ค:
โ€ข Redis Cluster์™€ ์ƒค๋”ฉ ์ „๋žต
โ€ข CDN ์บ์‹ฑ๊ณผ ์—ฃ์ง€ ์ปดํ“จํŒ…
โ€ข ์บ์‹œ ์ผ๊ด€์„ฑ ํ”„๋กœํ† ์ฝœ (MESI, MOESI)
โ€ข ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์—์„œ์˜ ์บ์‹œ ๋ฌดํšจํ™”
โ€ข Memcached vs Redis ๋น„๊ต
โ€ข ์บ์‹œ ์›Œ๋ฐ์—… ์ „๋žต
โ€ข TTL ์ž๋™ ์กฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜

์‹ค์Šต ํ”„๋กœ์ ํŠธ ์•„์ด๋””์–ด:
โ€ข ๋ธ”๋กœ๊ทธ ํ”Œ๋žซํผ ์บ์‹ฑ ์‹œ์Šคํ…œ
โ€ข ์‹ค์‹œ๊ฐ„ ์ฑ„ํŒ… ์„œ๋ฒ„ ์ตœ์ ํ™”
โ€ข API ๊ฒŒ์ดํŠธ์›จ์ด ์บ์‹ฑ
โ€ข ์ด๋ฏธ์ง€ ํ”„๋ก์‹œ ์„œ๋ฒ„
โ€ข ๊ฒ€์ƒ‰ ์—”์ง„ ๊ฒฐ๊ณผ ์บ์‹ฑ

๐ŸŽ‰ ์ถ•ํ•˜ํ•ด! ์ด์ œ ๋„ˆ๋Š” Go ์บ์‹ฑ ์ „๋ฌธ๊ฐ€์•ผ! ๐ŸŽ‰

Happy Coding! ๐Ÿ’ปโœจ

๋Œ“๊ธ€ ์ž‘์„ฑ

์ด ๊ธ€์— ๋Œ€ํ•œ ์—ฌ๋Ÿฌ๋ถ„์˜ ์ƒ๊ฐ์„ ๋“ค๋ ค์ฃผ์„ธ์š”

๋Œ“๊ธ€ 0
๋Œ“๊ธ€์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘์ž…๋‹ˆ๋‹ค.

์•„์ง ๋Œ“๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.