๐Ÿ—๏ธ Architecture

Partitioning

Data Partitioning

Logically divides large data. Range, hash, and list methods.

๐Ÿ“– Detailed Explanation

Partitioning is a database technique that divides a large table or index into multiple smaller units based on logical criteria and stores them that way. Managing hundreds of millions of rows or more in a single table causes problems such as degraded query performance, index bloat, and increased management complexity, and partitioning can resolve these problems. Logically it is one table, but physically it is stored as multiple partitions, so it can be accessed transparently.

Range Partitioning divides data based on ranges of continuous values such as dates and numbers. It is suitable for time-series data; for example, if you create partitions by month, queries over a specific period scan only the relevant partitions, greatly improving performance. Hash Partitioning distributes data evenly based on the hash value of a specific column, and is effective when the data distribution is irregular. List Partitioning divides data based on a list of specific values, and is used for explicit groupings such as region codes or status values.

Composite Partitioning combines two or more partitioning methods. For example, Range-Hash first creates range partitions by date, and then creates subpartitions by hash within each partition. This provides the advantages of both time-based queries and even distribution. Also, Partition Pruning is an optimization technique that scans only the partitions matching the query conditions, and it is a core benefit of partitioning.

Partitioning and Sharding are often confused but are different concepts. Partitioning divides a table within a single database, while sharding distributes data across multiple database servers. Modern distributed databases (Vitess, CockroachDB, TiDB) combine the two concepts to provide horizontal scalability. Partitioning is an essential technique for efficiently storing and querying large training datasets in AI/ML workloads, and Hive-style partitioning is also widely used in data lakes.

๐Ÿ’ป Code Example

PostgreSQL Range Partitioning

-- ๋ถ€๋ชจ ํ…Œ์ด๋ธ” ์ƒ์„ฑ (ํŒŒํ‹ฐ์…˜ ์ •์˜)
CREATE TABLE orders (
    id BIGSERIAL,
    order_date DATE NOT NULL,
    customer_id INTEGER,
    amount DECIMAL(10, 2),
    status VARCHAR(20)
) PARTITION BY RANGE (order_date);

-- ์›”๋ณ„ ํŒŒํ‹ฐ์…˜ ์ƒ์„ฑ
CREATE TABLE orders_2024_01 PARTITION OF orders
    FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');

CREATE TABLE orders_2024_02 PARTITION OF orders
    FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');

CREATE TABLE orders_2024_03 PARTITION OF orders
    FOR VALUES FROM ('2024-03-01') TO ('2024-04-01');

-- ๊ธฐ๋ณธ ํŒŒํ‹ฐ์…˜ (๋ฒ”์œ„์— ํฌํ•จ๋˜์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐ์šฉ)
CREATE TABLE orders_default PARTITION OF orders DEFAULT;

-- ํŒŒํ‹ฐ์…˜๋ณ„ ์ธ๋ฑ์Šค ์ž๋™ ์ƒ์„ฑ
CREATE INDEX idx_orders_customer ON orders (customer_id);
CREATE INDEX idx_orders_status ON orders (status);

-- ์ฟผ๋ฆฌ ์‹œ ํŒŒํ‹ฐ์…˜ ํ”„๋ฃจ๋‹ ํ™•์ธ
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE order_date BETWEEN '2024-02-01' AND '2024-02-29';
-- orders_2024_02 ํŒŒํ‹ฐ์…˜๋งŒ ์Šค์บ”๋จ

-- ํŒŒํ‹ฐ์…˜ ๋ถ„๋ฆฌ (์˜ค๋ž˜๋œ ๋ฐ์ดํ„ฐ ์•„์นด์ด๋ธŒ)
ALTER TABLE orders DETACH PARTITION orders_2024_01;
-- ๋…๋ฆฝ ํ…Œ์ด๋ธ”๋กœ ๋ณ€ํ™˜๋˜์–ด ์•„์นด์ด๋ธŒ ๊ฐ€๋Šฅ

MySQL Hash Partitioning

-- ํ•ด์‹œ ํŒŒํ‹ฐ์…”๋‹์œผ๋กœ ๊ท ๋“ฑ ๋ถ„์‚ฐ
CREATE TABLE user_sessions (
    session_id BIGINT NOT NULL,
    user_id INT NOT NULL,
    created_at DATETIME,
    data JSON,
    PRIMARY KEY (session_id, user_id)
)
PARTITION BY HASH(user_id)
PARTITIONS 8;

-- ๋ฆฌ์ŠคํŠธ ํŒŒํ‹ฐ์…”๋‹ (์ง€์—ญ๋ณ„)
CREATE TABLE customers (
    id INT NOT NULL,
    name VARCHAR(100),
    region VARCHAR(20),
    PRIMARY KEY (id, region)
)
PARTITION BY LIST COLUMNS(region) (
    PARTITION p_asia VALUES IN ('KR', 'JP', 'CN', 'TW'),
    PARTITION p_europe VALUES IN ('DE', 'FR', 'UK', 'IT'),
    PARTITION p_america VALUES IN ('US', 'CA', 'BR', 'MX'),
    PARTITION p_others VALUES IN (DEFAULT)
);

-- Range-Hash ๋ณตํ•ฉ ํŒŒํ‹ฐ์…”๋‹
CREATE TABLE access_logs (
    id BIGINT NOT NULL,
    access_time DATETIME NOT NULL,
    user_id INT,
    endpoint VARCHAR(255),
    PRIMARY KEY (id, access_time, user_id)
)
PARTITION BY RANGE (YEAR(access_time))
SUBPARTITION BY HASH(user_id)
SUBPARTITIONS 4 (
    PARTITION p2023 VALUES LESS THAN (2024),
    PARTITION p2024 VALUES LESS THAN (2025),
    PARTITION p2025 VALUES LESS THAN (2026)
);

-- ํŒŒํ‹ฐ์…˜ ์ •๋ณด ์กฐํšŒ
SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS, DATA_LENGTH
FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_NAME = 'access_logs';

Python + Apache Spark Partitioning

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, year, month

spark = SparkSession.builder \
    .appName("DataPartitioning") \
    .getOrCreate()

# ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
df = spark.read.parquet("s3://datalake/raw/events/")

# Hive ์Šคํƒ€์ผ ํŒŒํ‹ฐ์…”๋‹์œผ๋กœ ์ €์žฅ
df.write \
    .partitionBy("year", "month", "day") \
    .mode("overwrite") \
    .parquet("s3://datalake/partitioned/events/")

# ๊ฒฐ๊ณผ ๋””๋ ‰ํ† ๋ฆฌ ๊ตฌ์กฐ:
# s3://datalake/partitioned/events/
# โ”œโ”€โ”€ year=2024/
# โ”‚   โ”œโ”€โ”€ month=01/
# โ”‚   โ”‚   โ”œโ”€โ”€ day=01/
# โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ part-00000.parquet
# โ”‚   โ”‚   โ””โ”€โ”€ day=02/
# โ”‚   โ””โ”€โ”€ month=02/
# โ””โ”€โ”€ year=2025/

# ํŒŒํ‹ฐ์…˜ ํ”„๋ฃจ๋‹์ด ์ ์šฉ๋œ ์ฝ๊ธฐ
df_january = spark.read.parquet("s3://datalake/partitioned/events/") \
    .where(col("year") == 2024) \
    .where(col("month") == 1)
# year=2024/month=01 ํŒŒํ‹ฐ์…˜๋งŒ ์Šค์บ”

# Dynamic Partition Overwrite
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
df_updates.write \
    .partitionBy("year", "month") \
    .mode("overwrite") \
    .parquet("s3://datalake/partitioned/events/")
# ์—…๋ฐ์ดํŠธ๋œ ํŒŒํ‹ฐ์…˜๋งŒ ๋ฎ์–ด์“ฐ๊ธฐ

# Repartitioning (๋ฉ”๋ชจ๋ฆฌ ๋‚ด ์žฌ๋ถ„ํ• )
df_balanced = df.repartition(100, col("customer_id"))
df_coalesced = df.coalesce(10)  # ํŒŒํ‹ฐ์…˜ ์ˆ˜ ์ค„์ด๊ธฐ

# Bucket์„ ์‚ฌ์šฉํ•œ ์กฐ์ธ ์ตœ์ ํ™”
df.write \
    .bucketBy(32, "customer_id") \
    .sortBy("order_date") \
    .saveAsTable("orders_bucketed")

Automatic Partition Management Script

import psycopg2
from datetime import datetime, timedelta

def manage_partitions(conn, table_name: str, months_ahead: int = 3, months_retain: int = 24):
    """
    ํŒŒํ‹ฐ์…˜ ์ž๋™ ์ƒ์„ฑ ๋ฐ ์ •๋ฆฌ

    - ๋ฏธ๋ž˜ N๊ฐœ์›” ํŒŒํ‹ฐ์…˜ ๋ฏธ๋ฆฌ ์ƒ์„ฑ
    - ๋ณด๊ด€ ๊ธฐ๊ฐ„ ์ดˆ๊ณผ ํŒŒํ‹ฐ์…˜ ๋ถ„๋ฆฌ/์‚ญ์ œ
    """
    cursor = conn.cursor()
    today = datetime.now()

    # ๋ฏธ๋ž˜ ํŒŒํ‹ฐ์…˜ ์ƒ์„ฑ
    for i in range(months_ahead):
        target_date = today + timedelta(days=30 * i)
        partition_name = f"{table_name}_{target_date.strftime('%Y_%m')}"
        start_date = target_date.replace(day=1)
        end_date = (start_date + timedelta(days=32)).replace(day=1)

        create_sql = f"""
        CREATE TABLE IF NOT EXISTS {partition_name}
        PARTITION OF {table_name}
        FOR VALUES FROM ('{start_date.strftime('%Y-%m-%d')}')
        TO ('{end_date.strftime('%Y-%m-%d')}');
        """

        try:
            cursor.execute(create_sql)
            print(f"Created partition: {partition_name}")
        except psycopg2.errors.DuplicateTable:
            pass  # ์ด๋ฏธ ์กด์žฌ

    # ์˜ค๋ž˜๋œ ํŒŒํ‹ฐ์…˜ ๋ถ„๋ฆฌ
    cutoff_date = today - timedelta(days=30 * months_retain)

    cursor.execute(f"""
        SELECT schemaname, tablename
        FROM pg_tables
        WHERE tablename LIKE '{table_name}_%'
    """)

    for schema, partition in cursor.fetchall():
        try:
            partition_date = datetime.strptime(
                partition.replace(f"{table_name}_", ""),
                "%Y_%m"
            )
            if partition_date < cutoff_date:
                cursor.execute(f"ALTER TABLE {table_name} DETACH PARTITION {partition}")
                cursor.execute(f"DROP TABLE {partition}")
                print(f"Dropped old partition: {partition}")
        except ValueError:
            continue

    conn.commit()

# ๋งค์ผ ์‹คํ–‰ํ•˜์—ฌ ํŒŒํ‹ฐ์…˜ ๊ด€๋ฆฌ
if __name__ == "__main__":
    conn = psycopg2.connect("postgresql://localhost/mydb")
    manage_partitions(conn, "orders", months_ahead=3, months_retain=24)

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "The order table has passed 1 billion rows and queries have slowed down. If we apply Range partitioning by date, monthly queries will definitely get faster."
  • "If we create 8 partitions with hash partitioning, the data should be distributed evenly, and it looks like the hotspot issue will be resolved."
  • "Let's check with EXPLAIN whether partition pruning is working properly. The WHERE clause must include the partition key."
  • "If we store data in the data lake with Hive partitioning in a year/month/day structure, Athena query costs will also drop significantly."
  • "Please explain the differences between Range, Hash, and List partitioning. In which situations is each one suitable?"
  • "What is the difference between partitioning and sharding? When should each be chosen?"
  • "What is partition pruning, and why is it important? In which cases does pruning not work?"
  • "What operational aspects should be considered when applying partitioning to a large table?"

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "This query scans all partitions because the partition key column (order_date) is not in the WHERE clause. Please add a partition key condition."
  • "I think we need a script to create partitions automatically. Creating them manually every month can lead to mistakes."
  • "If we use a Local index instead of a Global index, managing indexes per partition becomes easier."

โš ๏ธ Cautions

Partition key design

The partition key should be included in most query conditions. Querying without the partition key scans all partitions, which can actually degrade performance. Also, the partition key is difficult to change, so it must be chosen carefully.

Partition Count Limits

Too many partitions (thousands or more) increase metadata management overhead and lengthen query planning time. Choose an appropriate unit (monthly, weekly, etc.) so that each partition contains enough data.

Joins and Foreign Key Constraints

In PostgreSQL, partitioned tables have limitations in foreign key constraint support. When joining across partitions, if the partition key is included in the join key, it is optimized with a Partition-Wise Join; otherwise, performance may degrade.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More