Compressed File StoreCompressed File StoreCFSCompressed File Store
The Compressed File Store (CFS) provides transparent,
page-level compression for heap, index, materialized view, and
TOAST relations. Compression and decompression happen
only at the storage-manager boundary, so the shared buffer cache, the
write-ahead log, and every higher layer continue to operate on ordinary
uncompressed BLCKSZ pages and are unaffected by CFS.
When a relation is enabled for CFS, its main fork is stored in three
sidecar files kept alongside the (otherwise empty)
base main-fork file. The sidecar files are created when the relation's
compression policy is published: at relation creation, at every
relfilenumber rewrite, and whenever relation data is copied to a new
relfilenumber (tablespace copies and CREATE DATABASE ...
STRATEGY WAL_LOG). They exist even before the first write, the
same way the base file exists from creation. The free-space map, visibility
map, and init forks are never compressed. Temporary
(TEMP) and unlogged (UNLOGGED)
relations cannot use CFS.
CFS Sidecar FilesSuffixPurpose.cfp
Append-only compressed page data. Each record is a
CfsCompressedBlockHeader followed by the
(possibly compressed) payload and alignment padding.
.cfsmap
Page map snapshot: a dense array of CfsMapEntry
records, indexed by logical block number.
.cfsjrn
Page map journal: a crash-safe, append-only sequence of mapping
updates applied on top of the last snapshot.
At checkpoint time the sidecar files are persisted in the order
.cfp, then .cfsjrn, then
.cfsmap. This ordering guarantees that a map entry
never points at a compressed record that has not reached durable storage.
Recovery starts from the latest .cfsmap snapshot and
folds the .cfsjrn journal into it row by row; the
fold is idempotent by (block number, generation) and
stops cleanly at the first torn record.
Like ordinary relation files, the .cfp data file is
segmented at 1 GB boundaries
(RELSEG_SIZE blocks): the first segment is named
.cfp, subsequent ones
.cfp.N. The
physical_offset stored in
CfsMapEntry is a global byte offset across the
whole segment chain; a record never crosses a segment boundary — when it
would not fit, the append cursor advances to the next boundary, leaving a
short unwritten padding at the segment tail. Because offsets were always
global, a .cfp written before segmentation needs no
conversion: every offset in it is below the boundary and therefore
addresses segment 0. A segment larger than
CFS_SEGMENT_SIZE is treated as corruption at open
time, since the engine never produces one. Compaction, checkpoint fsync,
relation drop, pg_upgrade and the integrity
checker all walk the segment chain transparently. The map and journal
files are single-segment by design.
The write-ahead log is unchanged: logical WAL records and full-page images
describe uncompressed pages, so CFS is an implementation detail of the
storage manager and does not affect WAL record format.
Build Configuration
CFS is enabled by default. It can be disabled entirely at build time, in
which case the src/backend/storage/cfs/ subsystem is
omitted and every integration point in the core server is compiled out under
the USE_CFS preprocessor guard; the resulting server then
behaves like upstream PostgreSQL and contains no
CFS symbols.
CFS Build OptionsBuild SystemEnable (Default)Disableautoconfmeson or
CFS does not depend on an external library of its own; it combines with
and/or the same
way TOAST compression does. When neither is given, the
built-in raw (pass-through) codec remains available and
only the lz4 / zstd algorithms become
unavailable.
Removing a codec that was available when existing CFS relations were
populated does not make those relations disappear, but it does make their
already-compressed pages unreadable: any attempt to read a block stored
with an algorithm the running binary no longer has fails with an error,
even though the relation's algorithm reloption still
names it. Rebuilding with the original library, or rewriting the affected
relations with ALTER TABLE ... SET (algorithm = ...)
before removing it, avoids this.
Enabling CFS for a Relation
CFS is enabled for a relation by setting the algorithm
reloption. Its absence means the relation uses ordinary uncompressed
storage; the global parameters below never enable CFS by themselves.
algorithm (enum)
Compression algorithm. Accepted values are lz4 and
zstd. Setting this option makes the relation a CFS
relation. The internal raw mode is not a user-visible
choice.
level (integer)
Compression level. lz4 accepts
1 to 12, zstd
accepts 1 to 22. When omitted,
the level is resolved at physical write time from the writing process's
cfs_default_lz4_level or
cfs_default_zstd_level, whichever matches the
algorithm.
min_gain_bytes (integer)
Minimum byte savings required for a page to be stored compressed instead
of raw. Only meaningful together with algorithm.
When omitted, the value is resolved at physical write time from the writing process's
cfs_default_min_gain_bytes.
The catalog stores only what was spelled out in the reloptions:
algorithm is the CFS marker, and
level / min_gain_bytes are optional.
A partial set of options is valid; nothing is copied from the
configuration parameters at DDL time. The following parameters supply
the runtime values used when an optional reloption is not specified, and
never enable CFS:
cfs_default_lz4_level (integer, default 1)
Compression level used for lz4 relations that do
not store an explicit level. The default follows
the library's fast mode (LZ4_compress_default).
Range 1 to 12.
cfs_default_zstd_level (integer, default 3)
Compression level used for zstd relations that do
not store an explicit level. Range 1 to 22.
cfs_default_min_gain_bytes (integer, default 512)
Minimum byte savings used for relations that do not store an explicit
min_gain_bytes.
Unset fields are resolved by the process performing the physical write.
A backend writing a page itself uses its session settings, while the
checkpointer and background writer use their own settings from the
server configuration. A session SET does not set
the compression level of a later background write, including a write
requested by CHECKPOINT.
This is safe — every compressed record carries its own algorithm
marker, and decompression never needs the level, so reads never
depend on any configuration parameter — and the effective policy for the calling session is observable
through pg_cfs_relation_info (see
). Setting an explicit
level (or min_gain_bytes) pins the
value for every writer; ALTER TABLE ... RESET removes
it and returns the field to runtime resolution.
The algorithm, level and
min_gain_bytes reloptions apply uniformly to every
built-in index access method (btree,
hash, gin, gist,
spgist, brin); CFS is not limited to
a specific index type.
An index is a CFS relation if and only if its own reloptions carry a
policy. An index without an explicit algorithm
inherits, at CREATE INDEX time, the parent table's
stored algorithm together with only those
level / min_gain_bytes values
the table stores explicitly; the index's own unset fields resolve at
runtime. After that the index is independent of the table: a later
ALTER TABLE ... SET (algorithm = ...) changes only
the table and never the indexes that already exist, and
ALTER INDEX ... RESET (algorithm) disables index
compression for good — a subsequent REINDEX keeps
the index plain. A TOAST relation never
stores CFS options of its own: its effective policy is resolved
through the owning table at the moment of each operation. Specifying
CFS reloptions in the toast. namespace (for
example toast.algorithm='lz4') is rejected with an
error, whether in CREATE TABLE, CREATE
TABLE AS, or a later ALTER TABLE ... SET
(toast.algorithm=...).
A partitioned table may store an explicit default policy (only the
keys spelled out on the parent) for future partitions but is never
itself a physical CFS relation.
CFS remains unsupported for TEMP and
UNLOGGED relations; the persistence check is repeated
during the rewrite phase of ALTER TABLE, so a combined
ALTER TABLE ... SET (algorithm = ...), SET UNLOGGED
cannot create the forbidden configuration.
For example, a table enabled without an explicit
level follows the session parameter of every writer:
CREATE TABLE events (id int, payload text) WITH (algorithm = 'zstd');
SET cfs_default_zstd_level = 7;
INSERT INTO events SELECT g, 'row ' || g FROM generate_series(1, 100) g;
SET cfs_default_zstd_level = 11;
INSERT INTO events SELECT g, 'row ' || g FROM generate_series(101, 200) g;
-- both batches are readable regardless of the parameter value
ALTER TABLE events SET (level = 9); -- pin an explicit level for everyone
ALTER TABLE events RESET (level); -- back to runtime resolution
Page I/O
Each storage-manager operation (smgrreadv,
smgrwritev, smgrextend,
smgrzeroextend, smgrtruncate,
smgrnblocks, smgrprefetch,
smgrimmedsync) consults the
smgriscfsenabled() predicate and, for a compressed main
fork, routes the call through the CfsStorageOps dispatch table
instead of the regular md path. Non-compressed forks
and ordinary relations are entirely unaffected.
Write path.FlushBuffer() applies the normal page checksum with
PageSetChecksumCopy() and then calls
smgrwritev(); the CFS write path compresses that
already-checksummed page, appends the record to
.cfp, appends a journal update, and updates the
in-memory map. The previous record is left in place and becomes
unreachable until compaction reclaims it.
Read path.
On a cache miss the asynchronous read entry point
smgrstartreadv() looks up the page map, reads the
compressed record from .cfp, verifies the block and
payload checksums, and decompresses the page directly into the caller's
buffer. PageIsVerified() then still performs its
header sanity checks; with cfs_skip_page_checksum on
(the default) the redundant cluster page-checksum computation is skipped
for these pages, and turning the parameter off restores the exact
ordinary-relation validation. Blocks whose records are
physically contiguous in one .cfp segment (for
example after a compaction, or in a relation whose pages were flushed
in block order, such as a freshly built index) are batched:
smgrmaxcombine() reports the length of the
contiguous run, and one pread() serves the whole
run, with each record still validated and decompressed individually.
Blocks that cannot join a run — rewritten pages, extension holes,
segment boundaries — are read per-block exactly as before, and the
grouping is re-derived at read time, so it never affects correctness.
Because a compressed page cannot be served by a raw
pread() alone, smgrstartreadv()
decompresses the requested blocks synchronously in the originating backend
and completes the AIO handle inline; batching removes
the per-record pread() calls, not the synchronous
decompression. smgrprefetch() advises the operating
system to read the .cfp ranges backing the requested
blocks into the page cache (posix_fadvise() with
POSIX_FADV_WILLNEED, one advice per contiguous record
run): decompression itself still cannot be deferred to an asynchronous
I/O callback and happens synchronously wherever the page is actually
needed, but the advice warms the page cache those decompressing reads
consume, so read-ahead hints do benefit CFS relations —
pg_prewarm(..., 'prefetch') works for them like for
ordinary relations. smgrwriteback(), driven by
bgwriter_flush_after,
checkpoint_flush_after and
backend_flush_after, likewise starts kernel writeback
of the dirty .cfp ranges
(sync_file_range(), Linux only; a no-op elsewhere).
Both are scheduling hints without any fsync semantics — durability
remains the checkpoint's business. The
read_stream pipeline still helps CFS tables only
through the combined transfers (bounded by
io_combine_limit): the decompression time itself
stays in the originating backend. Longer term, hosting codec state in
I/O workers remains the upgrade path. When a batched multi-block read
fails, the synchronous path reports the exact failing block, while the
AIO result channel has no room for a block number
and the report names the first block of the I/O.
When the cluster is initialised with , the
page checksum is part of the stored payload and survives the
compress/decompress round-trip. The additional CFS
orig_crc field is an independent integrity check,
verified during decompression before the buffer manager
checks the page checksum: with cfs_skip_page_checksum on
(the default) that later check is skipped as redundant, because the CRC
chain has already verified the exact page bytes, and setting the parameter
to off restores it.
Checkpoint, fsync and Background Compaction
CFS sidecar files (.cfp,
.cfsmap, .cfsjrn) are registered
in the standard sync queue through a dedicated
SYNC_HANDLER_CFS handler, so the checkpointer fsyncs
them at checkpoint time exactly like ordinary relation segments. Unlink of
permanent sidecar files is deferred to the next checkpoint; in redo and temp
paths the files are removed immediately.
At checkpoint time CfsCheckpoint() folds the journal
of every relation written since the previous checkpoint into its
.cfsmap in place: the volume of map writes is
proportional to the number of changed blocks, not to the relation size
(the cumulative checkpoint_map_rows_written
counter of
shows the exact number). The fold phase runs without the append lock -
writers keep appending during it - and each rewritten row carries its own
checksum, so a crash mid-fold leaves torn rows that the intact journal
repairs on the next load. A short phase under the exclusive append lock
then folds the records appended after the first phase stopped, fsyncs
their data and the journal first, and resets the journal to a bare
header; only a torn tail - the crash artifact, with nothing valid behind
it - is dropped by that reset. The reset header carries the bumped
incarnation plus the generation watermark of the map
state the reset leaves behind. The durability sequence
fsync(.cfp) -> fsync(.cfsjrn) -> fold .cfsmap -> reset
.cfsjrn therefore never loses a record a concurrent writer
appended.
The CFS background compaction worker is a launcher
that, like the autovacuum launcher, is not bound to any particular
database: every cfs_bg_period_ms it enumerates the
databases of the cluster from pg_database (databases
with datallowconn set to false are not
serviced) and, one database at a time, starts a short-lived worker that
connects to the database, scans its pg_class for CFS
relations whose dead-space ratio exceeds
cfs_bg_threshold and compacts their sidecar files
under a ShareUpdateExclusiveLock (online compaction,
cfs_compact_online; ordinary reads and writes of the
relation are not blocked, only short exclusive windows around the
snapshot and the final swap remain). The same compaction can
be triggered synchronously with the SQL function
pg_cfs_compact(regclass). Compaction does not
change the relfilenode and generates no WAL. Every
cfs_bg_* parameter (and
cfs_compact_online) can be changed with a
configuration reload (SIGHUP), unlike
cfs_map_cache_rels_per_partition and
cfs_stats_slots_per_partition, which are fixed at
server start.
cfs_map_cache_rels_per_partition (integer)
Number of relation-metadata slots per shared-memory map-cache
partition. The map cache tracks, for every known CFS relation, its
logical size and the dirty-for-checkpoint flag that
CfsCheckpoint() uses to decide which relations
need a fresh .cfsmap snapshot and a journal
truncate. The total number of CFS relations tracked cluster-wide is
64 times this value. Each slot also holds the relation's
append_lock, so a relation cannot be written or
checkpointed without one: when every slot of a partition is pinned
or dirty, an attempt to use a new relation fails with an error
naming this parameter instead of silently skipping the relation.
Default 16, range 1 to
64. This parameter is set at server start.
cfs_stats_slots_per_partition (integer)
Number of relation-statistics slots per shared-memory statistics
partition; the total number of CFS relations tracked in
pg_stat_cfs
is 64 times this value. Counters are atomic and updated under a
shared partition lock, so accounting does not serialize concurrent
readers and writers. When more CFS relations than the capacity are
active, statistics rows evict each other: the least recently used
row is reset to zero and reused for a new relation, so the view
silently loses older counters. Raise this parameter to cover the
working set of compressed relations. Default 16
(1024 relations cluster-wide), range 4 to
128. This parameter is set at server start.
Lowering the value discards the persisted statistics on the next
restart when the saved entry count exceeds the new capacity: the
saved file is validated against the new capacity as a whole and is
then dropped.
cfs_map_memory (integer)
Size in megabytes of the shared block-map segment pool, modelled
after shared_buffers. The pool holds the
per-relation logical block to .cfp
offset map in fixed 768 kB segments in shared memory,
shared by all backends instead of per-process private copies. A
segment is loaded from the .cfsmap snapshot on
first use and stays resident across checkpoints; a full pool evicts
segments by a clock sweep: every lookup and every write bumps the
segment's usage counter, the sweep decrements counters and reuses
the first segment whose counter reached zero. All resident
segments compete equally, regardless of whether their relation
currently has an open handle: an open handle pins the relation's
metadata slot, not its pool segments, and a scan's working set is
kept resident by the usage counters alone, exactly like the buffer
cache.
Sizing lower bound: the pool must hold the segment
working set you want to keep warm, where the
bound is measured in segments, not relations:
with the default segment span a 100 GiB relation is about 400
segments. A pool smaller than the working set evicts and reloads
cold segments (one 768 kB .cfsmap range plus
the journal delta per reload), which costs extra I/O but never
correctness, and the pool keeps adapting to whatever is actually
read. Only when every segment is in flight or hot (no victim for
the sweep) does a read fall back to the authoritative on-disk
state, counted in fallback_reads of
pg_cfs_map_pool(): one 768 kB
.cfsmap range plus the journal delta is read
per miss, and nothing is published into the pool. Size the pool
for the segments you want to keep warm.
Read-mostly relations whose working set is larger than the pool
can thrash it: lookups bump a segment's usage counter under the
segment lock, but a segment that is not looked up during a full
clock revolution is evicted in favour of the next segment that is
loaded. The counter is reset when a segment is evicted or its
relation is invalidated, so a recycled pool slot always starts
cold. This costs extra I/O, never correctness; size the pool for
the working set you want to keep warm.
The actual shared-memory reservation is somewhat larger than
cfs_map_memory: the parameter buys the segment
data itself, and the server additionally reserves the segment
descriptors, one lock per segment, the segment lookup and
per-relation index hashes, and the in-flight reservation table.
The pool is sized and its shared memory is reserved at server
start, even when no CFS relation is opened. This reservation is
deliberate: the pool is part of the server's fixed shared-memory
budget and its size must not depend on when the first CFS relation
appears. A value with a unit suffix is accepted, for example
128MB; a bare number is taken as megabytes.
Setting the parameter to 0 disables the pool
entirely: every handle then carries its own full private map, as
before the pool existed, and every block entry is resolved through
that map. Default 128, range
0 to 1048576. This
parameter is set at server start.
The default stays at 128: measurements with
32, 64 and
128 megabytes showed no throughput or residency
difference for a working set that already fits the smallest pool,
so the larger default is kept as headroom for many concurrently
open relations.
cfs_bg_threshold (integer)
Minimum dead-space percentage for a relation to be a compaction
candidate. The percentage is computed against the live volume
(the sidecar size minus the counted dead bytes), so a relation
whose live tail has been rewritten away is not masked by the dead
space compaction is about to reclaim. Default 10.
cfs_compact_online (boolean)
Enables online compaction. When on (the default), the background
worker and pg_cfs_compact() take
ShareUpdateExclusiveLock on the relation and
copy it in three phases with only short exclusive append-lock
windows at the start and the end, so ordinary reads and writes of
the relation keep running during the copy. When off, the same
ShareUpdateExclusiveLock is taken, but the
internal append lock is held for the whole operation, so writes to
the sidecar files are serialized until compaction finishes (plain
reads are not blocked). This parameter can be changed at any time
by reloading the configuration (it is signaled with
SIGHUP).
cfs_bg_respond_time_s (integer)
Timeout in seconds for the background worker to acquire the
compaction lock on a relation
(ShareUpdateExclusiveLock in both modes); on
timeout the candidate is skipped. The manual
pg_cfs_compact() call blocks until the lock
is granted. Default 5.
cfs_bg_delay_ms (integer)
Pause in milliseconds between compactions of relations in one pass.
Default 100.
cfs_bg_period_ms (integer)
Interval in milliseconds between compaction passes. Default
3600000 (one hour).
cfs_bg_min_interval_s (integer)
Minimum interval in seconds between compactions of the same relation.
Default 86400 (one day).
cfs_bg_max_relations (integer)
Maximum number of relations to compact per pass. Default
2.
Normal VACUUM (without FULL) does not
trigger CFS compaction and does not interact with the background worker.
Use pg_cfs_compact() or VACUUM FULL
/ CLUSTER to reclaim dead space.
DDL Lifecycle and Object Operations
CFS reloptions are stored in pg_class and travel
with the relation through all standard PostgreSQL DDL operations.
The following commands preserve CFS behaviour automatically:
VACUUM FULL / CLUSTER
Rewrite the heap into a new relfilenumber. The CFS reloptions are
copied to the new relation; sidecar files are recreated for the new
relfilenumber and the old sidecars are removed. Dead records are not
copied, so the physical size of .cfp shrinks.
REINDEX
Rebuilds the index into a new relfilenumber. The rebuilt index
keeps the index's own stored CFS policy: a compressed index is
rebuilt compressed, and an index without a policy of its own is
rebuilt plain whatever the parent table's policy is.
ALTER TABLE/INDEX ... SET TABLESPACE
Copies the relation files into the new tablespace. The relation's
CFS policy is published for the new relfilenumber before the copy
starts, so the data is written through the CFS write path and the
sidecar files are recreated in the new tablespace. The TOAST table
and its indexes follow the parent table's policy.
ALTER TABLE ... SET (algorithm = 'lz4'|'zstd')
Changing the algorithm triggers a full table rewrite so that every
page is stored in the new compression format. This applies when
enabling CFS on a plain table, switching between algorithms, or
resetting the algorithm back to plain storage. Existing indexes
are not affected: each index keeps the policy frozen in its own
reloptions.
ALTER INDEX ... SET/RESET (algorithm)SET (algorithm = 'lz4'|'zstd') stores the policy
in the index's own reloptions and triggers an implicit
REINDEX of that index alone, rather than a
rewrite of the underlying table. RESET (algorithm)
removes the policy and rebuilds the index as a plain relation;
compression stays disabled for good — a later
REINDEX rebuilds plain storage again, never the
table's policy.
ALTER TABLE ... SET (level|min_gain_bytes)
Changing the compression level or minimum gain threshold updates the
reloptions only; no table rewrite occurs. The new values apply to
pages written after the change.
ALTER TABLE ... RESET (level|min_gain_bytes)
Removes the explicit value from the reloptions and returns the field
to runtime resolution from the session parameters of each writer; no
table rewrite occurs. Resetting the
algorithm itself switches the relation back to
plain storage and requires a rewrite.
CREATE DATABASE ... TEMPLATE
When the template database contains CFS relations, the file-level
copy publishes each source relation's CFS policy for the
corresponding relation in the new database before the first page is
copied, so the copy is written through the CFS write path from the
start instead of landing in the new relation's plain main fork.
CFS is not supported for TEMP or
UNLOGGED relations. CREATE TEMP TABLE ...
WITH (algorithm=...) and CREATE UNLOGGED TABLE ...
WITH (algorithm=...) are rejected. ALTER TABLE ...
SET UNLOGGED on a CFS table is also rejected.
A partitioned table may store an explicit default policy for future
partitions. New partitions created with CREATE TABLE
... PARTITION OF ... inherit exactly the keys the parent
stores explicitly — the algorithm plus, when set on
the parent, level and
min_gain_bytes — unless they specify their own CFS
reloptions. Unset fields on either side resolve at runtime from the
physical writer's parameters. Changing the partitioned root's default
is a catalog-only change: it does not rewrite or otherwise affect
existing partitions.
Normal VACUUM (without FULL) does
not trigger CFS compaction (see )
and does not modify the .cfp file; it updates the
visibility map and statistics by the same rules as for an ordinary
table.
Crash Recovery, WAL and Replication
CFS does not introduce its own WAL resource manager. The WAL stream
always contains standard uncompressed page images; compression happens
only at the storage-manager write boundary. Durability of CFS sidecar
files is achieved through the append-only .cfp
data file, the idempotent .cfsjrn journal, and the
checkpoint-snapshot .cfsmap.
On startup after a crash, CfsRecoveryInit()
scans the data directories for .cfsjrn files and
folds each journal into its page map row by row, through the same
engine the checkpoint uses, before accepting client connections. The
fold is idempotent and handles torn final records gracefully; only the
rows the journal names are rewritten, so the recovery scan's cost is
proportional to the journal (the changes since the last checkpoint),
never to the relation size: the scan itself loads no map into memory
and rewrites no snapshot. In a clean restart this is a fast
no-op because journals were truncated at the last checkpoint. As a
consequence, a .cfsmap row corrupted without a
covering journal record is not touched at startup: the damage
surfaces at the first access of that block, through the normal
checksum-failure policy.
The journal records logical-size changes through the
RESIZE operation, ensuring that
smgrnblocks() returns the correct block count
after crash recovery even when the last operations before the crash
were TRUNCATE or COPY
(zero-extend).
pg_basebackup copies CFS sidecar files as part of
the normal backup. A standby initialised from the backup can read
CFS tables immediately, and WAL replay writes dirty pages through the
CFS storage path. WAL redo prefetching remains a no-op for CFS
relations — the startup prefetcher skips them, since a compressed
record cannot be prefetched usefully ahead of the decompressing redo
read — while user-level read-ahead hints do warm the
.cfp page cache (see ).
Whether a server was built with CFS support is reported to every
client, including physical replication connections, as a read-only
parameter. When a standby connects to start streaming, it compares
this value against its own build and refuses the connection if they
differ, in either direction, before requesting any WAL — a CFS-built
primary and a non-CFS standby (or vice versa) cannot stream from each
other. If the mismatch is only discovered later, for example when
replaying archived WAL during point-in-time recovery without ever
opening a streaming connection, replay of the CFS policy record on a
server without CFS support stops recovery with a clear error instead
of an unrecognized-record-type failure. Logical replication is not
affected, since it never replays physical WAL records.
Compaction cannot commit while any non-exclusive base backup is in
progress: swapping the .cfp/.cfsmap
pair underneath a running backup would let it assemble a mismatched
sidecar trio that WAL replay cannot repair. A manual
pg_cfs_compact() call fails with an error during
a backup, and the background compaction worker skips the pass.
pg_basebackup --incremental handles the
.cfp data files with an append-only tail diff.
The first bytes of every .cfp form a lead-in that
records the file-creation epoch: it changes only
when the file is replaced wholesale (relation creation, compaction
swap), never during append-only growth. Every backup manifest entry
for a .cfp file carries two fork-specific fields,
CFS-Epoch and CFS-Logical-Size.
When the next incremental backup sees the same epoch and a size not
smaller than the recorded logical size, only the blocks covering the
grown tail are sent, inside an incremental file whose header
(fork-specific magic INCREMENTAL_CFS_MAGIC) stores
the exact byte size of the file; pg_combinebackup
truncates the reconstruction to that size, because a
.cfp file is not aligned to the block size.
Otherwise — a legacy file with zero epoch, an epoch mismatch after
compaction, a shrunk file, or a file missing from the prior manifest —
the file is backed up fully. The .cfsmap and
.cfsjrn files are rewritten wholesale at
checkpoints and are always copied fully. Note that manifests carrying
the CFS fields are a fork extension of the manifest format and are
rejected by upstream PostgreSQL tools.
pg_rewind synchronises CFS sidecar files as
ordinary files, copying them in full from the source; the empty main
fork marker of a CFS relation never takes part in the per-block
rewinding. When the target replays the source WAL from the last
common checkpoint, every CFS page modified after the copy began is
rewritten through the CFS storage path, which makes the result
consistent. To keep a compaction swap from racing the copy on a
running source server, pg_rewind holds a
non-exclusive backup on the source for the duration of the transfer
whenever CFS sidecar files are present; the connection to the source
therefore needs privileges to run pg_backup_start()
and pg_backup_stop() in addition to the usual
pg_rewind permissions. A stopped source server
needs no such quiesce.
cfs_checksum_failure (enum)
Controls the severity when a CFS CRC or format check — including
structural damage such as an invalid .cfsmap
prologue or .cfsjrn header — fails during a
normal backend read. error (default) raises an
error, and panic aborts the server. This
parameter is superuser-only and is set at session level. A
warning mode is intentionally not provided,
because silently substituting data on corruption would cause
divergence between primary and standby.
cfs_skip_page_checksum (boolean)
When true (the default), the buffer manager skips
the cluster page-checksum computation for pages delivered by the CFS
read path, because the CFS CRC chain (header, payload and
original-image CRCs) has already verified the exact bytes; the
header sanity checks of PageIsVerified() are
always performed. When false, the second
full-page hash is restored (the double-check behaviour). This
parameter is superuser-only and is set at session level. The
decision is bound at I/O submit time in the
originating backend, so a session changing it affects only reads
whose I/Os are submitted afterwards.
cfs_recovery_strict (boolean)
When true, journal record corruption encountered
during crash recovery is treated as a fatal error rather than being
tolerated: a skipped record (whose referenced data file contents are
missing) and a torn record with data still following it both abort
startup. A torn final record — the normal
artifact of a crash mid-append — stays non-fatal in both modes. A
corrupt .cfsmap or
.cfsjrn header is fatal in every mode,
independently of this parameter: the map header is a synchronisation
point whose data WAL does not cover, and a journal header that fails
validation means the file cannot be trusted to describe itself.
Default is false. This parameter is set at
server start.
Monitoring and SQL Interface
CFS exposes its configuration, runtime statistics and administration
surface through a set of system views and functions. All of them are
available in the pg_catalog schema and visible to
every role that can see the underlying relation.
The pg_cfs_settings view lists the stored CFS policy
of every supported relation: whether it is compressed
(is_cfs), the
algorithm, level
and min_gain_bytes, and the classification
flags (is_toast,
is_index,
is_partitioned_root,
is_supported). A
level or
min_gain_bytes field the relation does not
store explicitly is reported as 0, not resolved from
the session parameters. Because 0 is also a valid
min_gain_bytes value (its range starts at 0),
a zero there does not by itself distinguish an unset field from an
explicit 0; the
level_effective and
min_gain_effective columns of
pg_cfs_relation_info resolve the unset fields from
the current session's parameters and disambiguate the two cases.
Ordinary relations appear with is_cfs set to
false.
The pg_stat_cfs view reports one row per CFS relation
with its algorithm, the logical and physical
sizes, the number of compressed and uncompressed pages, the dead-space
counters
(dead_pages,
dead_bytes), the derived
compression_ratio and
space_saved, the operation counters
(read_count, write_count,
compress_count,
decompress_count), the batched-read counters
(read_batch_count,
read_batched_pages,
read_fallback_pages), the number of
crc_failures, and the
last_reset and
last_compaction timestamps. The
batched-read counters attribute every page served through the storage
manager either to a physically contiguous span read (one
pread per run of neighbouring records) or to the
per-block fallback path; the invariant
read_count = read_batched_pages +
read_fallback_pages
holds in both map modes (on a private map the per-block reads are
counted by neither side, mirroring the historical read_count
behaviour), and
read_batched_pages / read_batch_count is
the average span length in pages.
Both counters describe the last checkpoint:
dead_bytes is recomputed from the relation
map and the physical data size - an advisory snapshot of the
checkpoint's map refresh, so records a writer appends during the
checkpoint itself are not yet in it (the value never understates the
dead space) - and
dead_pages accumulates the superseded page
versions the checkpoint folds carried (a folded record that replaced
a previously written row is one dead page version). Between
checkpoints the counters hold the last checkpoint's values. The cumulative
checkpoint_map_rows_written counter shows
how many map rows the checkpoints folded into the map for the
relation: it grows with the number of blocks changed between
checkpoints, not with the size of the map, because a checkpoint
writes only the journal's records into the map (the full map
snapshot is written only by an immediate sync). The
counter counts folded journal records, not distinct rows: a block
rewritten several times between checkpoints adds one per rewrite,
because the fold carries every record the journal holds.
The counters are cleared by an explicit
pg_cfs_reset_stats call; a statistics row evicted
under capacity pressure also restarts from zero (see below).
In particular, crc_failures is not
cleared when the shared map cache of a relation is invalidated (for
example after the very read failure that incremented it, or when the
relation is dropped), so a non-zero value always means real corruption
was observed since the last explicit reset or eviction of the
relation's row.
The view holds one statistics row per relation in a fixed-size
shared-memory table of
cfs_stats_slots_per_partition slots per partition
(1024 relations with the default). When more CFS relations than
that are active, rows evict each other: the least recently used row
is reset to zero and its counters are lost; when the relation
becomes active again, its counters restart from zero. Counters are
updated atomically under a shared lock, so the view may combine
values read at slightly different instants - each counter is exact
on its own, the same consistency model as cumulative statistics of
the core server.
The counters are saved to a file at a regular shutdown and restored
at the next startup, so a maintenance restart does not lose the
dead-space bookkeeping the automatic compactor relies on. After a
crash (or immediate) restart the restored
dead_bytes may predate the crash, so it
is recomputed from the relation's page map at the first
measurement: by the background compactor's first full cycle over
the cluster's databases (relations without a saved entry included)
and by the relation's next checkpoint, which rebuilds its baseline
from the map it has just folded.
dead_pages cannot be derived from the
map and keeps the restored value. A clean restart performs no
recomputation - the saved values are current - unless the previous
clean shutdown overtook the recomputation still pending after an
earlier crash restart, in which case it runs on that clean start
as well.
The diagnostic functions are:
pg_cfs_relation_info(regclass)
Returns a single row describing the effective CFS policy of a relation
and its classification (heap, index, TOAST, partitioned root,
supported). Policy fields the relation does not store explicitly
are returned as NULL; the
level_effective and
min_gain_effective columns resolve the
unset fields from the current session's parameters, the same way
the write path does.
pg_cfs_relation_size(regclass)
Returns the logical size and the size of each CFS sidecar file
(cfp_size, map_size,
journal_size).
pg_cfs_check(regclass, boolean DEFAULT false)
Runs the structural integrity checker over the sidecar files. With
deep set to true every block header in the
.cfp file is validated. The checker streams the
files in bounded-size chunks, so sidecars larger than 1
GB are validated the same way as small ones, and it
walks every .cfp.N
segment. A map row that is corrupt but still covered by a journal
record is reported as healed
(healed_entries in the details) instead of damage,
and the set of such rows kept in memory is bounded. Journal records
are additionally checked for
generation monotonicity per block: a zero
generation is reported as corruption, while a non-increasing
sequence is counted as an anomaly
(generation_violations) without failing
the check, because concurrent backends may legitimately compute the
generation from a stale local map. A non-CFS relation
returns ok=true, is_cfs=false without raising an
error. The function is strict: a NULL argument returns NULL.
pg_cfs_estimate_compression(regclass, text, integer DEFAULT NULL, real DEFAULT 10)
Compresses a random sample of the relation's pages in memory with the
named algorithm and level and reports the estimated compression ratio
and space that would be saved, without writing anything to disk or
changing the reloptions. Useful to gauge the benefit of CFS before
running ALTER TABLE ... SET (algorithm=...).
The sample is drawn at random, like the one used by
ANALYZE, so repeated calls on the same relation
may return slightly different numbers.
A NULL relation, algorithm or
sample_pct raises an error; a NULL
level selects the per-algorithm session default.
The administrative functions pg_cfs_compact,
pg_cfs_check,
pg_cfs_estimate_compression,
pg_cfs_reset_stats,
pg_cfs_bgworker_pause and
pg_cfs_bgworker_resume are not executable by
PUBLIC: by default only a superuser can call them,
and access may be delegated with an explicit
GRANT EXECUTE. Independently of the function
privilege, pg_cfs_compact requires ownership of
the target relation, mirroring the permission model of
VACUUM FULL and CLUSTER.
pg_cfs_check and
pg_cfs_estimate_compression are closed for the
same reason as pg_read_file(): the former, with
deep=true, reads and validates every byte of the
sidecars, and the latter reads and compresses a share of the
relation's real pages — in both cases a single call costs IO and
CPU proportional to the sampled data, without requiring any
privilege on the relation itself. The lightweight read-only
diagnostics (pg_cfs_relation_info,
pg_cfs_bgworker_status) and the monitoring
views remain available to all roles.
pg_cfs_reset_stats(regclass DEFAULT
NULL) clears the pg_stat_cfs counters, including
crc_failures, for one relation, or for every
CFS relation in the cluster when called with no argument (or an explicit
NULL).
Compaction is administered separately from the table reloptions (see
). The synchronous function
pg_cfs_compact(regclass) rewrites the
sidecar files of one relation and records the completion time in
pg_stat_cfs.last_compaction. By default it runs
online under ShareUpdateExclusiveLock
(cfs_compact_online enabled): ordinary reads and
writes of the relation keep running during the rewrite. When
cfs_compact_online is off, the same
ShareUpdateExclusiveLock is taken, but the internal
append lock is held for the whole operation, so writes to the sidecar
files are serialized until compaction finishes (plain reads are not
blocked). The background worker acquires the lock with the
cfs_bg_respond_time_s timeout and skips the
candidate on timeout; the manual function blocks until the lock is
granted. The progress of an in-progress compaction (manual or
automatic) is visible through
pg_stat_progress_cfs_compact, which reports the
phase
(initializing, copying live blocks,
transferring concurrent appends or
durable swap), the total and processed block counts
and the started_at timestamp.
The automatic background compactor can be suspended temporarily with
pg_cfs_bgworker_pause(interval), which
accepts an optional duration, and resumed with
pg_cfs_bgworker_resume(). The current state is
returned by pg_cfs_bgworker_status(), which reports
whether the worker is currently paused, the
paused_until timestamp if a duration was
given, and the last_cycle_started_at and
last_cycle_finished_at timestamps of the most
recent pass. A pause does
not interrupt an already-running compaction and does not affect manual
pg_cfs_compact calls; it is cleared automatically on
server restart.
The shared block-map segment pool (see
cfs_map_memory) is observed through
pg_cfs_map_pool(), a single row with the number of
segments currently held (segments_in_use),
how many were loaded from the .cfsmap snapshot
(segment_loads), how many were reclaimed by
eviction (segment_evictions), the total
pool capacity (pool_segments) and how many
reads were served through a private authoritative map because no
segment was available (fallback_reads). A
stable segment_loads across checkpoints
confirms that resident segments stay warm instead of being re-read by
every backend; a growing
fallback_reads means the pool is undersized
for the current working set.
CFS reports six IO-class wait events visible in
pg_stat_activity
and pg_wait_events: CfsRead,
CfsWrite, CfsFsync,
CfsJournalReplay, CfsCompact and
CfsDecompress. CfsRead covers
the pread of a record or a record span only, while
CfsDecompress covers the validation and
decompression of the records, so wait-event sampling can attribute the
read phase (IO) and the decompression phase (CPU) independently.
Standard Utilities and Contrib
CFS is designed so that the standard PostgreSQL tooling works on a
cluster that uses compressed relations without special procedures. The
sidecar files live alongside the relation main-fork file and are
enumerated, copied and verified by the usual mechanisms.
Size functionspg_relation_size(regclass,
'main') for a CFS relation returns the physical
on-disk size of the main fork, which includes the
.cfp, .cfsmap and
.cfsjrn sidecar files (the base main-fork file is
only a compatibility marker). This lets users compare a compressed
relation against a plain one and see the actual space savings.
pg_total_relation_size,
pg_database_size and
pg_tablespace_size include sidecar bytes through
the same path or via directory enumeration.
Physical backupspg_basebackup
copies sidecar files as ordinary files (they are not in any exclusion
list), and the backup manifest records their SHA-256 checksums. A
restored backup starts up and reads CFS relations normally.
pg_verifybackup
verifies sidecar integrity through the manifest; a corrupted
.cfp is detected exactly like any other file
mismatch.
pg_checksums
Page-level checksums do not apply to sidecar files, which carry their
own CRC-32C integrity protection.
pg_checksums
recognises the .cfp, .cfsmap
and .cfsjrn suffixes (including numbered
.cfp.N segments),
skips them and reports the number of skipped files both in
output and in the final summary.
pg_upgradepg_upgrade
transfers .cfp, .cfsmap and
.cfsjrn for every relation using the same
clone/copy/link mode as the main fork. Before any file is moved the
upgrade performs a compatibility scan of the old cluster's
.cfsmap headers and aborts with a clear message if
an incompatible on-disk format is detected, so that an upgrade never
leaves a half-migrated cluster. The on-disk format version is checked
again by the server when the relation is opened after the upgrade.
Contrib extensionspageinspect,
amcheck and
pgstattuple
require no CFS-specific changes: they read pages through the buffer
manager, which transparently returns decompressed
BLCKSZ pages, so all existing functions
(get_raw_page, verify_heapam,
bt_index_check, pgstattuple,
etc.) work unchanged on CFS tables and CFS-inherited indexes.