Skip to content

AxonOps — AI-Native Control Plane for Open Source Data Platforms

Cassandra Commit Log

The commit log is Cassandra's write-ahead log (WAL), providing durability for all mutations. Every write is appended to the commit log before being acknowledged, ensuring data can be recovered after a crash.

For an overview of how the commit log fits into the write path, see Write Path.


The commit log serves a single purpose: crash recovery. It is not used for reads. All read operations go through memtables and SSTables.

GuaranteeDescription
DurabilityAcknowledged writes survive node restart
OrderingMutations are replayed in segment order; correctness relies on mutation timestamps
AtomicityIndividual mutations are atomic (all-or-nothing)

Commit Log vs Replication

The commit log provides single-node durability. For cluster-wide durability, Cassandra relies on replication. With RF=3 and QUORUM writes, data survives even if one node loses its commit log before flushing.


The commit log is organized into segments: fixed-size files that are allocated, filled, and eventually deleted.

Commit Log Segment LifecycleCommit Log Segment LifecycleSegment PoolActive SegmentsCleanupAvailableSegmentAvailableSegmentAllocatingSegment(current)ActiveSegment(awaiting flush)ActiveSegment(awaiting flush)CleanSegment(all tables flushed)DeletedMutations appended hereSwitches when size limit reachedSafe to delete:all dirty intervalshave been flushedallocationsegment full(> 32MB)all referencedmemtables flushed
StateDescription
AvailableAllocated, empty, queued for use
AllocatingCurrently receiving mutations
ActiveFull (reached commitlog_segment_size_in_mb), awaiting memtable flush
CleanAll referenced data flushed to SSTables; segment is deleted

Cassandra keeps a pool of ready segments so that a new segment is always available when the current one fills. Segments are allocated on demand and are not pre-allocated to their full size on disk.

Memory-mapped segments (default): The segment file is created and memory-mapped. The file grows as mutations are appended, up to commitlog_segment_size_in_mb.

Compressed/encrypted segments: Mutations are buffered in memory and written in blocks. The on-disk size depends on compression ratio.

Historical: Pre-allocation and Recycling (removed in 2.2)

Segments are created as needed rather than pre-allocated to their full size. Modern Cassandra deletes segments when clean rather than recycling them.

Each segment maintains a map of which table mutations it contains and their position ranges:

Segment: CommitLog-7-1702345678901.log
Dirty Intervals:
┌─────────────────┬────────────────────┐
│ Table ID │ Position Range │
├─────────────────┼────────────────────┤
│ users │ [1024, 15360] │
│ orders │ [2048, 31744] │
│ events │ [8192, 28672] │
└─────────────────┴────────────────────┘

When a memtable flushes, it reports its commit log position range. The segment marks those intervals as clean. Once all intervals are clean, the segment is deleted.


Each segment file contains a header followed by sync blocks of serialized mutations.

┌─────────────────────────────────────────────────────────────┐
│ HEADER │
├──────────┬───────────┬─────────────┬────────────┬───────────┤
│ Version │ Segment │ Params Len │ Params │ Header │
│ (4 bytes)│ ID (8) │ (2 bytes) │ (JSON) │ CRC (4) │
└──────────┴───────────┴─────────────┴────────────┴───────────┘
┌─────────────────────────────────────────────────────────────┐
│ SYNC BLOCK 1 │
├─────────────────────────────────────────────────────────────┤
│ Sync Marker: [next block offset (4) | marker CRC (4)] │
├─────────────────────────────────────────────────────────────┤
│ Mutation 1: [size (4) | size CRC (4) | data | data CRC (4)] │
│ Mutation 2: [size (4) | size CRC (4) | data | data CRC (4)] │
│ ... │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ SYNC BLOCK 2 │
│ ... │
└─────────────────────────────────────────────────────────────┘
FieldSizeDescription
Version4 bytesCommit log format version
Segment ID8 bytesUnique segment identifier
Parameters length2 bytesLength of JSON parameters (unsigned short)
ParametersVariableJSON: compression/encryption settings
Header CRC4 bytesCRC32 checksum of header

Each sync block begins with a marker indicating the offset to the next block:

FieldSizeDescription
Next offset4 bytesFile position of next sync block
Marker CRC4 bytesCRC32 of the offset value
FieldSizeDescription
Size4 bytesSerialized mutation size
Size CRC4 bytesCRC32 of size field
DataVariableSerialized mutation bytes
Data CRC4 bytesCRC32 of mutation data

The dual CRC design (size + data) allows detection of both truncation and corruption during replay.


The sync mode controls when data is flushed from OS page cache to persistent storage, and whether a mutation is acknowledged before or after that flush.

Parameter names differ across the versions covered here. Cassandra 5.0 and 4.1 use duration literals. Cassandra 4.0 uses the older _in_ms forms, which 5.0 and 4.1 still accept as deprecated aliases.

commitlog_sync: periodic
commitlog_sync_period: 10000ms # 4.0: commitlog_sync_period_in_ms: 10000

Mutations are written to the page cache and acknowledged immediately. A background thread calls fsync() once per sync period.

Periodic sync mode: acknowledge from page cache, fsync laterClientClientCassandraCassandraPage CachePage CacheDiskDiskClientClientCassandraCassandraPage CachePage CacheDiskDiskWrite mutationwrite() to page cacheAcknowledge (fast)10 seconds laterfsync()Flush to diskConfirmedData in page cache only.Power loss = data loss.After fsync, data survivespower failure.

Trade-off: Lowest latency, at the cost of acknowledging writes that are not yet on disk. The window is longer than one sync period. Writers block once the sync thread falls behind by more than periodic_commitlog_sync_lag_block, which is 1.5 sync periods by default. What that window costs depends on how the node stopped; see What Is Lost When a Node Stops.

commitlog_sync: batch # 5.0, 4.1 and 4.0; no interval parameter

Batch mode calls fsync() on each write and acknowledges the write only after that call returns. No parameter controls the interval. Cassandra 5.0 removed the old batch window key (CASSANDRA-17161), and a node does not start if the key is present. On 4.1 and 4.0 the key is deprecated but tolerated under batch mode, where it is ignored. Under periodic mode its presence stops the node starting. Grouping happens only by accident, when writes arrive while a sync is already in flight and are covered by the next one.

Batch sync mode: each write triggers an fsync before acknowledgementClient 1Client 2CassandraDiskClient 1Client 1Client 2Client 2CassandraCassandraDiskDiskWrite Afsync() [A]The sync starts at once; there is no windowWrite BArrives while the sync is in flightConfirmedAcknowledge Afsync() [B]ConfirmedAcknowledge B

Trade-off: The highest fsync rate and the lowest throughput. No acknowledged write is left off disk, and each write waits for one fsync.

commitlog_sync: group
commitlog_sync_group_window: 1000ms # 4.0: commitlog_sync_group_window_in_ms: 1000

Group mode acknowledges a write only after fsync(), as batch mode does, so durability is the same in both. They differ in when the sync happens. The group sync thread waits up to commitlog_sync_group_window, and the writes that arrive inside that window share one fsync(): fewer syncs, higher write latency. A write waits up to one window plus the fsync, not a full window every time.

There is no working default. Group mode does not start until a window is set. The shipped cassandra.yaml of 5.0, 4.1 and 4.0 comments out an example of 1000 milliseconds, shown above. A window that size can add up to a second to every write, so it is a starting point for testing rather than a recommendation.

Modefsync triggerWindowWrite acknowledgedAcknowledged writes at risk
periodicBackground thread, once per sync period10 seconds by defaultBefore fsyncUp to 1.5 sync periods by default
groupGroup sync thread, once per windowNo default; shipped example 1000msAfter fsyncNone
batchEach writeNoneAfter fsyncNone

The last column is what is at risk when the host is lost. Losing the Cassandra process alone costs far less, as described next.

Periodic mode is the only mode that acknowledges a write before it is durable, so it is the only mode with a window to lose. How much of that window is lost depends on what stopped. Losing the Cassandra process and losing the host have different bounds. The behaviour below is the same on Cassandra 5.0, 4.1 and 4.0, and assumes the default commit log: uncompressed, unencrypted and memory mapped.

Clean shutdown. systemctl stop, nodetool drain and any other SIGTERM path runs the drain shutdown hook, which flushes memtables and syncs the commit log before the JVM exits. Nothing acknowledged is lost.

Loss of the process. A kill -9, an OOM kill or a JVM crash does not cost the sync window. Segments are memory mapped, so an acknowledged mutation is already in the OS page cache. The kernel writes those pages out whether the process survives or not. The bound comes from replay instead. The commit log is read in sections marked off by sync markers, and replay stops at the first marker that was never written. Markers are written every 100 milliseconds and the interval cannot be changed, so up to roughly the last 100 milliseconds of acknowledged writes on that node may go unreplayed. This bound applies only when the commit log is neither compressed nor encrypted.

Loss of the host. An OS crash, a hypervisor reset or a power failure discards the page cache, so the full unsynced window is lost: at the defaults, up to 1.5 times commitlog_sync_period, or 15 seconds.

Compression or encryption removes the process-kill bound

On Cassandra 5.0, 4.1 and 4.0, setting commitlog_compression or enabling transparent_data_encryption_options replaces memory-mapped segments with segments that hold mutations in JVM memory and write them to the file only at sync time. Acknowledged data then sits inside the process rather than in the page cache, so a kill -9 or an OOM kill loses the same window as a power failure: in periodic mode, up to 1.5 times commitlog_sync_period by default. The 100 millisecond bound does not apply.

Cassandra 5.0 added commitlog_disk_access_mode (CASSANDRA-18464), which selects how segments are written. The parameter does not exist in 4.1 or 4.0. Its default, legacy, reproduces the 4.1 and 4.0 behaviour.

Commit logcommitlog_disk_access_modeResultNode starts
Uncompressed, unencryptedlegacy (default) or mmapMemory-mapped segments. Losing the process costs about 100 milliseconds, as in 4.1 and 4.0.Yes
Uncompressed, unencryptedautodirect where the filesystem supports it and disk_optimization_strategy is ssd, otherwise memory-mapped segments.Yes
Uncompressed, unencrypteddirectSegments skip the page cache. Losing the process costs the full unsynced window, the same as losing the host.Only where the filesystem supports direct I/O; otherwise the node fails to start
Compressed or encryptedlegacy or autoResolves to standard. Losing the process costs the full unsynced window.Yes
Uncompressed, unencryptedstandardRejected as a configuration error.No
Compressed or encryptedstandardSegments buffered in the JVM. Losing the process costs the full unsynced window.Yes
Compressed or encryptedmmap or directRejected as a configuration error.No

At the cluster level, the coordinator sends every write to all replicas of the partition, so a write acknowledged at LOCAL_QUORUM with RF 3 in the local datacenter was still sent to all three of that datacenter's replicas. Losing it outright requires every replica that received it to lose its host inside the same window. Hinted handoff and repair rebuild the missing copies once a node returns. This is a statement about data safety alone and makes no claim about availability: a node that is down is unavailable for the ranges it holds whether or not its data survives elsewhere.

A restore does not recover writes lost in an unsynced window. The backup predates them, unless commit log archiving is configured for point in time recovery. A restore rolls data back to the backup point and discards every write made since, which can cost more data than the failure did. See Backup and Restore and Assess Node Failure.

A change data capture consumer has its own bound, and it is not the one above: the CDC index file records the offset of data already on disk, so a consumer that reads only up to that offset never sees an unsynced position. See CDC index files.


The segment type determines how data is written to disk.

# No special configuration - this is the default

Uses memory-mapped I/O. The segment is mapped into virtual memory, and writes go directly to the mapped region. The OS handles flushing based on sync mode.

Characteristics:

  • Simplest implementation
  • Relies on OS page cache management
  • No compression overhead
commitlog_compression:
- class_name: LZ4Compressor
parameters: {}

Mutations are compressed in memory before writing to disk.

AlgorithmClass NameRatioCPU
LZ4LZ4Compressor~2-3xVery low
SnappySnappyCompressor~2xLow
DeflateDeflateCompressor~4-5xHigh

Characteristics:

  • Reduces disk I/O
  • Smaller commit log footprint
  • Slight CPU overhead
  • Compression happens in fixed-size buffers before writing
transparent_data_encryption_options:
enabled: true
chunk_length_kb: 64
cipher: AES/CBC/PKCS5Padding
key_alias: testing:1
key_provider:
- class_name: org.apache.cassandra.security.JKSKeyProvider
parameters:
- keystore: conf/.keystore
keystore_password: changeit
store_type: JCEKS
key_password: changeit

Data is written in configurable-size blocks. Each block is compressed (if enabled) then encrypted.

Block Structure (Encrypted):

┌───────────────────────────────────────────┐
│ Total Block Length (unencrypted, 4 bytes) │
│ Encrypted Data Length (unencrypted, 4) │
│ Encrypted Data (variable) │
│ └── Contains: compressed mutation data │
└───────────────────────────────────────────┘

The length fields are unencrypted to allow reading block boundaries without decryption.


On startup, Cassandra replays commit log segments to recover mutations that weren't flushed to SSTables.

Commit log replay algorithm on startupCommit log replay algorithm on startupScan commitlog_directorySort segments by IDRead segment headerValidate header CRCHeader valid?yesnoRead sync markerValidate marker CRCMarker valid?yesnoRead mutation size + CRCSize CRC valid?yesnoRead mutation data + CRCData CRC valid?yesnoCheck if mutation's tablewas flushed after this positionNeeds replay?yesnoApply mutation to memtableSkip (already in SSTable)Log corruption, skip mutationLog corruption, skip to next blockyesMore mutations in block?Log corruption, skip segmentyesMore sync blocks?Skip corrupted segmentDelete replayed segmentyesMore segments?Replay complete

Not all mutations in a segment need replay. Each SSTable records the commit log position at flush time. During replay:

  1. Read mutation's commit log position
  2. Check if the mutation's table has an SSTable flushed after that position
  3. If yes, skip (data already durable in SSTable)
  4. If no, apply mutation to memtable
Corruption TypeDetectionRecovery
Header corruptionHeader CRC mismatchSkip entire segment
Sync marker corruptionMarker CRC mismatchSkip to next segment
Size field corruptionSize CRC mismatchSkip to next sync block
Data corruptionData CRC mismatchSkip mutation, continue
TruncationUnexpected EOFStop replay at truncation point

The CRC-based design allows partial recovery: corruption in one mutation does not prevent replaying subsequent valid mutations.


ParameterDefaultDescription
commitlog_directory$CASSANDRA_HOME/data/commitlogCommit log location
commitlog_segment_size_in_mb32Max segment size before switching
commitlog_total_space_in_mb8192Max total commit log space
Parameter (5.0, 4.1)Parameter (4.0)DefaultDescription
commitlog_synccommitlog_syncperiodicSync mode: periodic, batch or group
commitlog_sync_periodcommitlog_sync_period_in_ms10000ms / 10000, set in the shipped filePeriodic sync interval
periodic_commitlog_sync_lag_blockperiodic_commitlog_sync_lag_block_in_ms1.5 times the sync periodLag at which writers block waiting for a sync
commitlog_sync_group_windowcommitlog_sync_group_window_in_msUnset; the shipped file only comments an example of 1000ms / 1000Group mode window

Batch mode has no interval parameter on 5.0, 4.1 or 4.0.

ParameterDefaultDescription
commitlog_compressionnoneCompression algorithm configuration
ParameterDefaultDescription
transparent_data_encryption_options.enabledfalseEnable encryption
transparent_data_encryption_options.chunk_length_kb64Encryption block size
transparent_data_encryption_options.cipherAES/CBC/PKCS5PaddingCipher algorithm

RecommendationRationale
Dedicated disk/volumeIsolate commit log I/O from data I/O
Fast storage (NVMe/SSD)Commit log is write-intensive
Battery-backed cacheAllows safer periodic sync with durability
Separate from data_file_directoriesPrevents commit log from competing with compaction
Terminal window
# Check commit log size
du -sh /var/lib/cassandra/commitlog/
# Count segments
ls -1 /var/lib/cassandra/commitlog/*.log | wc -l
# Monitor via JMX
nodetool sjk mx -b "org.apache.cassandra.metrics:type=CommitLog,name=TotalCommitLogSize" -f Value
nodetool sjk mx -b "org.apache.cassandra.metrics:type=CommitLog,name=PendingTasks" -f Value
MetricDescriptionAlert Threshold
TotalCommitLogSizeCurrent size of all segments> 75% of commitlog_total_space_in_mb
PendingTasksMutations awaiting syncSustained high values
WaitingOnCommitTime waiting for fsync> 100ms average
WaitingOnSegmentAllocationTime waiting for new segmentShould be ~0
SymptomPossible CauseResolution
High WaitingOnCommitSlow disk, high loadFaster storage, tune sync mode
Growing commit logMemtables not flushingCheck memtable_flush_writers, disk space
Slow startupLarge commit log replayMore frequent flushing, check flush triggers
Segment allocation delaysDisk full or slowFree space, faster storage

VersionCassandraChanges
63.0 - 3.11Introduced with storage engine rewrite
74.0+Current format, improved checksums

See Segment Allocation for details on segment recycling removal in 2.2.