Skip to content

myeonghan-nim/database-sharding

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

database sharding

샀딩

λ°μ΄ν„°λ² μ΄μŠ€λ₯Ό μ—¬λŸ¬ 개둜 λ‚˜λˆ„λŠ” κ²ƒμœΌλ‘œ 각 μƒ€λ“œλŠ” μ„œλ‘œ λ‹€λ₯Έ 물리적 μ„œλ²„μ— 쑴재 κ°€λŠ₯. 각 μƒ€λ“œλŠ” λ…λ¦½μ μœΌλ‘œ μž‘λ™ν•˜λ©° 데이터λ₯Ό μ‚½μž…ν•  λ•Œ 데이터 뢄포 κ·œμΉ™μ— 따라 νŠΉμ • μƒ€λ“œμ— μ €μž₯. 샀딩을 κ΅¬ν˜„ν•˜λŠ” λ°λŠ” λ‹€μ–‘ν•œ μ „λž΅μ΄ 있으며 그쀑 κ°€μž₯ 많이 μ‚¬μš©λ˜λŠ” 것이 ν•΄μ‹œ 기반 μƒ€λ”©μœΌλ‘œ 이 방법은 νŠΉμ • ν‚€(예: μ‚¬μš©μž ID)에 λŒ€ν•œ ν•΄μ‹œ 값을 κ³„μ‚°ν•˜μ—¬ 데이터λ₯Ό μ–΄λ–€ μƒ€λ“œμ— μ €μž₯할지 κ²°μ •.

μ˜ˆμ‹œ

# settings.py
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "default.sqlite3",
    },
    "shard1": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "shard1.sqlite3",
    },
    "shard2": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "shard2.sqlite3",
    },
}

DATABASE_ROUTERS = ["path.to.db_router.ShardRouter"]

# db_router.py
import hashlib


class HashShardRouter:
    SHARDS = ["shard1", "shard2"]

    # ν•΄μ‹œ 기반으둜 μƒ€λ“œλ₯Ό 선택
    def get_shard(self, user_id):
        # SHA256 ν•΄μ‹œ μ‚¬μš© ν›„ 10μ§„μˆ˜λ‘œ λ³€ν™˜
        hash_val = int(hashlib.sha256(str(user_id).encode()).hexdigest(), 16)
        # μƒ€λ“œ 개수둜 λ‚˜λˆˆ λ‚˜λ¨Έμ§€ 연산을 톡해 μƒ€λ“œ 선택
        shard_index = hash_val % len(self.SHARDS)
        return self.SHARDS[shard_index]

    # 데이터λ₯Ό μ €μž₯ν•  λ°μ΄ν„°λ² μ΄μŠ€λ₯Ό κ²°μ •ν•˜λŠ” 둜직
    def db_for_write(self, model, **hints):
        if hasattr(model, "user_id"):
            return self.get_shard(model.user_id)
        return "default"

    # 데이터λ₯Ό 읽을 λ°μ΄ν„°λ² μ΄μŠ€λ₯Ό κ²°μ •ν•˜λŠ” 둜직
    def db_for_read(self, model, **hints):
        if hasattr(model, "user_id"):
            return self.get_shard(model.user_id)
        return "default"

μœ„μ™€ 같이 μ—¬λŸ¬ μƒ€λ“œλ₯Ό μ€€λΉ„ν•˜κ³  각각에 μ €μž₯ 및 λΆˆλŸ¬μ˜€κΈ°κ°€ κ°€λŠ₯

About

πŸ“– Study: database sharding

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages