Ver3.0 ๐ Go์ธ์ด ์บ์ฑ ์ ๋ต ์์ ์ ๋ณต: sync.Map๊ณผ Redis๋ก ์ฑ๋ฅ 10๋ฐฐ ๋์ด์ฌ๋ฆฌ๊ธฐ

๐ Go์ธ์ด ์บ์ฑ ์ ๋ต ์์ ์ ๋ณต: sync.Map๊ณผ Redis๋ก ์ฑ๋ฅ 10๋ฐฐ ๋์ด์ฌ๋ฆฌ๊ธฐ
์๋
! ์ค๋์ Go ์ธ์ด๋ก ๊ฐ๋ฐํ๋ฉด์ ๋๊ตฌ๋ ํ ๋ฒ์ฏค ๊ณ ๋ฏผํ๊ฒ ๋๋ ์บ์ฑ ์ ๋ต์ ๋ํด ๊น์ด ์๊ฒ ํํค์ณ๋ณผ ๊ฑฐ์ผ. ๐ฏ
์๋น์ค๊ฐ ์ปค์ง๋ฉด์ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๋ถํ๊ฐ ๊ฑฑ์ ๋๊ฑฐ๋, API ์๋ต ์๋๊ฐ ๋๋ ค์ ธ์ ๊ณ ๋ฏผ์ด๋ผ๋ฉด?
์ด ๊ธ์ด ๋ฐ๋ก ๋๋ฅผ ์ํ ์๋ฃจ์
์ด ๋ ๊ฑฐ์ผ! sync.Map๋ถํฐ Redis ํด๋ผ์ด์ธํธ ์ต์ ํ๊น์ง, ์ค์ ์์ ๋ฐ๋ก ์จ๋จน์ ์ ์๋ ๋
ธํ์ฐ๋ฅผ ์น๊ตฌ์ฒ๋ผ ํธํ๊ฒ ์๋ ค์ค๊ฒ. ๐
๐ก ์ ์บ์ฑ์ด ํ์ํ ๊น?
๊ฐ๋ฐํ๋ค ๋ณด๋ฉด ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๋ฐ๋ณตํด์ ์กฐํํ๋ ๊ฒฝ์ฐ๊ฐ ์์ฒญ ๋ง์.
์๋ฅผ ๋ค์ด ์ฌ์ฉ์ ํ๋กํ ์ ๋ณด, ์ํ ๋ชฉ๋ก, ์ค์ ๊ฐ ๊ฐ์ ๊ฒ๋ค ๋ง์ด์ผ.
๋งค๋ฒ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ๊ทผํ๋ฉด ์ด๋ค ์ผ์ด ๋ฒ์ด์ง๊น? ๐ค
โ ๏ธ ์บ์ฑ ์์ด ์ด์ํ ๋ ๋ฐ์ํ๋ ๋ฌธ์ ๋ค
โข ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ปค๋ฅ์
ํ ๊ณ ๊ฐ
โข ๋คํธ์ํฌ ๋ ์ดํด์ ๋์
โข CPU ์ฌ์ฉ๋ฅ ๊ธ์ฆ
โข ์๋ต ์๊ฐ ์ง์ฐ (์๋ฐฑ ms โ ์์ญ ms๋ก ๊ฐ์ ๊ฐ๋ฅ!)
โข ์๋ฒ ๋น์ฉ ์ฆ๊ฐ ๐ธ
์ค์ ๋ก ์บ์ฑ์ ์ ์ฉํ๋ฉด ์๋ต ์๋๊ฐ 10๋ฐฐ์์ 100๋ฐฐ๊น์ง ๋นจ๋ผ์ง๋ ๊ฒฝ์ฐ๋ ํํด.
ํนํ ์ฝ๊ธฐ ์์
์ด ๋ง์ ์๋น์ค๋ผ๋ฉด ์บ์ฑ์ ์ ํ์ด ์๋๋ผ ํ์์ผ!
์ฌ๋ฅ๋ท ๊ฐ์ ํ๋ซํผ์์๋ ์ฌ์ฉ์ ์ ๋ณด๋ ์ฌ๋ฅ ๋ชฉ๋ก์ ์บ์ฑํด์ ๋น ๋ฅธ ์๋น์ค๋ฅผ ์ ๊ณตํ๊ณ ์์ ๊ฑฐ์ผ.
๐ฅ Go์ sync.Map ์์ ๋ถ์
Go 1.9 ๋ฒ์ ๋ถํฐ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ํฌํจ๋ sync.Map์ ๋์์ฑ ํ๊ฒฝ์์ ์์ ํ๊ฒ ์ฌ์ฉํ ์ ์๋ ๋งต์ด์ผ.
์ผ๋ฐ map์ mutex๋ฅผ ๊ฑธ์ด์ ์ฐ๋ ๊ฒ๋ณด๋ค ํน์ ์ํฉ์์ ํจ์ฌ ๋น ๋ฅด๊ฑฐ๋ ! ๐
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 ์น๊ฒฉ ํธ๋ฆฌ๊ฑฐ
์ด๋ก ์ ์ด ์ ๋๋ก ํ๊ณ , ์ค์ ์ฝ๋๋ก ์ด๋ป๊ฒ ์ฐ๋์ง ๋ณผ๊น?
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๊ฐ ๋์ ๊ฒฝ์ฐ:
โข ์ฐ๊ธฐ ์์
์ด ๋น๋ฒํ ๊ฒฝ์ฐ
โข ํค๊ฐ ๊ณ์ ์ถ๊ฐ/์ญ์ ๋๋ ๊ฒฝ์ฐ
โข ๋จ์ผ ๊ณ ๋ฃจํด์์๋ง ์ ๊ทผํ๋ ๊ฒฝ์ฐ
์ค์ ๋ก ์ผ๋ง๋ ์ฐจ์ด๊ฐ ๋ ๊น? ๋ฒค์น๋งํฌ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ํ์คํ ์ ์ ์์ด.
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์ด ํ์คํ ์น์์ผ!
๐ฏ ์ค์ ์บ์ฑ ํจํด ๊ตฌํํ๊ธฐ
์ด์ ์ค๋ฌด์์ ๋ฐ๋ก ์ธ ์ ์๋ ๊ณ ๊ธ ์บ์ฑ ํจํด๋ค์ ์์๋ณผ๊ฒ.
๋จ์ํ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ๊บผ๋ด๋ ๊ฒ์ ๋์ด์, ํจ์จ์ ์ด๊ณ ์์ ์ ์ธ ์บ์ ์์คํ
์ ๋ง๋๋ ๋ฐฉ๋ฒ์ด์ผ.
๊ฐ์ฅ ๋ง์ด ์ฐ์ด๋ ํจํด์ด์ผ. ๋ฐ์ดํฐ๊ฐ ํ์ํ ๋๋ง ์บ์์ ๋ก๋ํ๋ ๋ฐฉ์์ด์ง.
๋ฉ๋ชจ๋ฆฌ๋ฅผ ํจ์จ์ ์ผ๋ก ์ธ ์ ์๊ณ , ๊ตฌํ๋ ์ง๊ด์ ์ด๋ผ์ ์ด๋ณด์๋ ์ฝ๊ฒ ์ ์ฉํ ์ ์์ด.
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)
}
๋ฐ์ดํฐ๋ฅผ ์ธ ๋ ์บ์์ 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
}
์ด๊ฑด ์ง์ง ์ค์ํ ํจํด์ด์ผ! ๐จ
์บ์๊ฐ ๋ง๋ฃ๋๋ ์๊ฐ ์๋ง์ ์์ฒญ์ด ๋์์ 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% ๊ฐ์ ๐
โข ์๋ต ์๊ฐ ์ผ๊ด์ฑ ํ๋ณด
โข ์์คํ
์์ ์ฑ ๋ํญ ํฅ์
์ฌ๋ฅ๋ท ๊ฐ์ ๋๊ท๋ชจ ํ๋ซํผ์์๋ ํ์์ ์ธ ํจํด์ด์ผ!
๐ Redis ํด๋ผ์ด์ธํธ ์ฑ๋ฅ ์ต์ ํ
์ด์ ๋ถ์ฐ ์บ์์ ์, 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๋ณด๋ค ์ฝ๊ฐ ๊ธธ๊ฒ ์ค์
โข ๋๋ฌด ๊ธธ๋ฉด ์๋ต ์ง์ฐ, ๋๋ฌด ์งง์ผ๋ฉด ์๋ฌ ์ฆ๊ฐ
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๊ฐ ์ด์)์ ํผํ๊ธฐ
โข ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋ ์ฆ๊ฐ ๊ฐ๋ฅ
โข ์๋ฌ ์ฒ๋ฆฌ๋ฅผ ๊ผผ๊ผผํ ํด์ผ ํจ
โข ๋ช
๋ น ๊ฐ ์์กด์ฑ์ด ์์ผ๋ฉด ์ฌ์ฉ ๋ถ๊ฐ
์ฌ๋ฌ 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)๋ฅผ ํจ๊ป ์ฐ๋ฉด ๋ ๋ง๋ฆฌ ํ ๋ผ๋ฅผ ๋ค ์ก์ ์ ์์ด.
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๋ฐฐ ๋น ๋ฆ! ๐
โก ์ค์ ์ฑ๋ฅ ํ๋ ์ฒดํฌ๋ฆฌ์คํธ
์ด์ ์ค๋ฌด์์ ๋ฐ๋ก ์ ์ฉํ ์ ์๋ ์ฑ๋ฅ ํ๋ ํ๋ค์ ์ ๋ฆฌํด๋ณผ๊ฒ.
์ด ์ฒดํฌ๋ฆฌ์คํธ๋ง ๋ฐ๋ผ๊ฐ๋ ์บ์ ์ฑ๋ฅ์ด ํ ๋ฌ๋ผ์ง ๊ฑฐ์ผ! ๐ช
๐ก ๋ฐ์ดํฐ ํน์ฑ๋ณ TTL ๊ฐ์ด๋
์ ์ ๋ฐ์ดํฐ (๊ฑฐ์ ์ ๋ฐ๋):
โข ์: ๊ตญ๊ฐ ๋ชฉ๋ก, ์นดํ
๊ณ ๋ฆฌ, ์ค์ ๊ฐ
โข TTL: 1์๊ฐ ~ 24์๊ฐ
โข ๋ณ๊ฒฝ ์ ๋ช
์์ ๋ฌดํจํ ํ์
์ค์ ์ ๋ฐ์ดํฐ (๊ฐ๋ ๋ฐ๋):
โข ์: ์ฌ์ฉ์ ํ๋กํ, ์ํ ์ ๋ณด
โข TTL: 5๋ถ ~ 30๋ถ
โข Write-Through ํจํด ๊ถ์ฅ
๋์ ๋ฐ์ดํฐ (์์ฃผ ๋ฐ๋):
โข ์: ์ฌ๊ณ , ์ข์์ ์, ์ค์๊ฐ ๋ญํน
โข TTL: 10์ด ~ 1๋ถ
โข Lua ์คํฌ๋ฆฝํธ๋ก ์์์ฑ ๋ณด์ฅ
์ด๋จ๊ธฐ ๋ฐ์ดํฐ:
โข ์: API ์์ฒญ ์ ํ, ์ธ์
ํ ํฐ
โข TTL: 1์ด ~ 10์ด
โข Redis๋ง ์ฌ์ฉ (L1 ๋ถํ์)
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...")
}
}
}
ํน์ ํค์ ์์ฒญ์ด ์ง์ค๋๋ฉด 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
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.