TOAST 내부 구조와 대형 값 저장
PostgreSQL이 지나치게 큰 열을 저장하는 방식을 이해하고 압축 및 외부 저장 임계값을 조정하는 방법을 배웁니다.
TOAST 내부 구조와 대형 값 저장은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 PostgreSQL Performance & Query Optimization 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why TOAST Exists
PostgreSQL stores rows on fixed-size 8 KB pages. A single row cannot span multiple pages, so a wide value (a long text, big jsonb, or bytea) would never fit.
TOAST (The Oversized-Attribute Storage Technique) solves this by compressing oversized columns and, if still too large, slicing them into chunks stored in a separate side table.
- Keeps the main heap row small and cache-friendly.
- Lets a logical value far exceed 8 KB (up to ~1 GB).
- Happens automatically and transparently to your queries.
The TOAST Threshold
TOAST kicks in when a row's total size would exceed TOAST_TUPLE_THRESHOLD, which is 2 KB (one quarter of the 8 KB page) by default.
When that limit is crossed, PostgreSQL compresses and/or moves the largest toastable attributes out of line until the row fits under TOAST_TUPLE_TARGET (also ~2 KB).
Only columns of variable-length types (text, varchar, jsonb, bytea, arrays, etc.) are toastable. Fixed-width types like integer or timestamptz are never toasted.
Finding the TOAST Table
Every table with at least one toastable column gets an associated TOAST table named pg_toast.pg_toast_<oid>. You can locate it from the catalog.
The reltoastrelid column links a heap relation to its TOAST relation; a value of 0 means no TOAST table was created.
SELECT c.relname,
c.reltoastrelid,
t.relname AS toast_table
FROM pg_class c
LEFT JOIN pg_class t ON t.oid = c.reltoastrelid
WHERE c.relname = 'documents';The Four Storage Strategies
Each column has a storage strategy controlling whether it can be compressed and/or moved out of line:
PLAIN— no compression, no out-of-line; only valid for non-toastable types.EXTENDED— allow both compression and out-of-line storage (default for most varlena types).EXTERNAL— allow out-of-line but no compression (faster substring access).MAIN— allow compression but keep in the main table unless absolutely necessary.
Inspecting Per-Column Storage
Query pg_attribute.attstorage to see each column's strategy. The codes map to: p=PLAIN, e=EXTERNAL, m=MAIN, x=EXTENDED.
SELECT attname,
atttypid::regtype AS type,
CASE attstorage
WHEN 'p' THEN 'plain'
WHEN 'e' THEN 'external'
WHEN 'm' THEN 'main'
WHEN 'x' THEN 'extended'
END AS storage
FROM pg_attribute
WHERE attrelid = 'documents'::regclass
AND attnum > 0
AND NOT attisdropped;Changing a Column's Strategy
Use ALTER TABLE ... SET STORAGE to override the default. A common optimization: if you frequently read random substrings of a large bytea (e.g. range reads on a blob), switch to EXTERNAL so values are stored uncompressed and can be partially fetched without decompressing the whole thing.
The new strategy applies only to rows written after the change; existing data is not rewritten until updated.
ALTER TABLE documents
ALTER COLUMN payload SET STORAGE EXTERNAL;
-- Force a rewrite to apply it to existing rows:
VACUUM FULL documents;Compression Algorithms: pglz vs lz4
PostgreSQL compresses TOAST values before considering out-of-line storage. Two algorithms are available:
pglz— the historic built-in, decent ratio, slower.lz4— available since PostgreSQL 14, much faster compress/decompress with a slightly lower ratio. Requires the server to be built with lz4 support.
The cluster-wide default is set by default_toast_compression.
SHOW default_toast_compression;
-- Set lz4 cluster-wide (postgresql.conf or per session):
SET default_toast_compression = 'lz4';Per-Column Compression
From PostgreSQL 14 onward you can set the compression method on individual columns with SET COMPRESSION. This is independent of the storage strategy.
Choose lz4 for hot, large columns where CPU during read/write matters; keep pglz or use EXTERNAL when ratio or substring access dominates.
ALTER TABLE documents
ALTER COLUMN body SET COMPRESSION lz4;
-- Inspect chosen method per column:
SELECT attname, attcompression
FROM pg_attribute
WHERE attrelid = 'documents'::regclass
AND attnum > 0;Tuning the Out-of-Line Target
The reloption toast_tuple_target controls how aggressively PostgreSQL pushes attributes out of line: it sets the size the main tuple is shrunk toward (valid range 128 bytes to ~8160).
Lowering it makes more values go to TOAST sooner, keeping the main heap dense and improving scan performance when the big columns are rarely read. Raising it keeps more data inline.
ALTER TABLE documents
SET (toast_tuple_target = 512);
-- Verify current reloptions:
SELECT reloptions
FROM pg_class
WHERE relname = 'documents';Measuring TOAST Footprint
Use the size functions to separate main-table bytes from TOAST bytes. This tells you whether your bloat lives in the heap or in oversized values.
pg_table_size— heap + TOAST + their indexes' TOAST, excluding regular indexes.pg_relation_size(rel, 'main')— just the main fork.
SELECT
pg_size_pretty(pg_relation_size('documents')) AS heap,
pg_size_pretty(
pg_total_relation_size(reltoastrelid)
) AS toast,
pg_size_pretty(pg_total_relation_size('documents')) AS total
FROM pg_class
WHERE relname = 'documents';Practical Performance Implications
TOAST is invisible until it isn't. Key effects to remember:
- Reading a toasted column triggers extra index lookups into the TOAST table and possible decompression — avoid
SELECT *when you only need small columns. - Values stay TOASTed across UPDATEs that don't touch them, so unrelated updates are cheap.
EXTERNALenables efficientsubstr()/ range reads on large uncompressed blobs.- Switching
pglztolz4can cut write CPU dramatically on insert-heavy large-value workloads.
Quick Check
You have a table whose large bytea column is read mostly via substr() on small byte ranges, and these reads are slow because each access decompresses the entire value. Which single change best fixes this?
Recap
You learned how PostgreSQL handles oversized values:
- TOAST triggers when a row would exceed the ~2 KB threshold, compressing then moving large varlena columns into
pg_toast.*tables. - Four strategies —
PLAIN,MAIN,EXTENDED(default),EXTERNAL— control compression and out-of-line placement, set viaALTER TABLE ... SET STORAGE. lz4(PG14+) offers faster compression thanpglz; choose per column withSET COMPRESSIONor cluster-wide viadefault_toast_compression.toast_tuple_targettunes how eagerly values leave the heap; size functions reveal how much storage lives in TOAST.- Pick
EXTERNALfor substring/range reads,lz4for write-heavy large values, and avoidSELECT *to skip needless detoasting.
자주 묻는 질문
“TOAST 내부 구조와 대형 값 저장” 강의는 무료인가요?
네 — “TOAST 내부 구조와 대형 값 저장” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
“TOAST 내부 구조와 대형 값 저장”에서 뭘 배우나요?
PostgreSQL이 지나치게 큰 열을 저장하는 방식을 이해하고 압축 및 외부 저장 임계값을 조정하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
PostgreSQL Performance & Query Optimization을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 PostgreSQL Performance & Query Optimization은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“TOAST 내부 구조와 대형 값 저장” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 PostgreSQL Performance & Query Optimization 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 PostgreSQL Performance & Query Optimization 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 테이블 및 인덱스 팽창 정확하게 측정하기
- pg_repack으로 공간 회수하기
- UPDATE가 많은 테이블의 Fillfactor 조정
- TOAST 내부 구조와 대형 값 저장