Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

RocketMQ Storage Engine: CommitLog, ConsumeQueue, PageCache & Flush Trade-offs

This article dissects RocketMQ's storage engine, explaining CommitLog hybrid storage, ConsumeQueue's fixed-length indexing, PageCache flush/replication mechanics, disk watermark thresholds, deletion policies, and capacity planning, with real incident analyses and source-code insights.

Introduction

The storage engine is the physical foundation of all RocketMQ guarantees. Disk physics has obeyed one rule for forty years: sequential access is ~100x faster than random access. Every storage design leans into this rule, and every "odd behavior" in send/consume traces back to a compromise made while leaning into that rule. Understanding the compromises lets you distinguish "by design" from "real bug" at incident scenes.

Three Main Threads

Write path single bridge : All topics share one CommitLog (default 1GB segments), turning multi-topic writes into a single sequential stream — the biggest model divergence from Kafka.

Read path two-level jump : ConsumeQueue fixed-length entries enable arithmetic positioning, pushing lookup cost to near zero.

Capacity three gates : Retention deletion, watermark deletion, watermark rejection — 90% of disk issues are miscalculated capacity, not bad hardware.

Incident Cases

Incident 1: Disk 85% Watermark Triggers Write Rejection

Pre-sale load test doubled write rate without disk expansion. Broker crossed 85% watermark and rejected writes; producer reported system errors. Monitoring showed green CPU/memory/connections — disk watermark wasn't on dashboard. Mitigation: emergency log cleanup. Root fix: add watermark alerts (70% warn, 85% reject), embed capacity formula in reviews.

Incident 2: OS_PAGECACHE_BUSY Spikes P99 to Seconds

No sustained high load, but send P99 spiked daily with OS_PAGECACHE_BUSY. Overlap with expiration deletion window: deletion thread batch-cleaning segments + fsync dirty pages + replication thread read lock collided on PageCache. Mitigation: shift deletion window away from peak, isolate co-located tasks. Root fix: smooth write rate (peak shaving), upgrade to NVMe.

Incident 3: Broker Restart Takes 40 Minutes Loading Indexes

Heavy-backlog broker planned restart; process up in 1 minute but ConsumeQueue recovery took 40 minutes — consumption unavailable, backlog worsened. Root cause: recovery rebuilds index state per queue; total entries (queue count × backlog depth) dictate load time. Mitigation: drain traffic first, use master-slave failover. Root fix: cap per-broker backlog (backlog is "unconsumed debt" recorded on storage engine).

Technical Analysis: Hybrid Storage Model

1.1 Write Path Single Bridge: All Topics Share One CommitLog

First-principle design: all topic messages append to the same CommitLog file sequence (default 1GB per segment). Disk sees only one sequential append stream. Topic/queue concepts exist only after the dispatch service "reconstructs" them post-CommitLog. This turns "multi-topic write" from a disk random-write problem into an in-memory routing problem: no matter how many topics write concurrently, disk sees one sequential flow.

Why essential for e-commerce? Topic count explodes: hundreds of business topics, each with several queues, total write points easily thousands. Kafka's independent partition logs degrade to random writes at this scale (masked by page cache and batching), while shared log is naturally immune — write throughput decouples from topic count, capacity planning only watches total write rate . Trade-off: read requires an extra index hop, write amplification borne by ConsumeQueue.

Overlooked benefit: uniform fault radius . Under partition-per-disk, a disk failure kills all partitions on that disk; shared log spreads writes evenly across disks, single disk failure affects "a small slice of all topics" not "entire individual topics" — finer recovery granularity, less uneven business impact. Critical for multi-tenant platforms: no tenant's topic becomes wholly unavailable due to single disk failure.

Why Kafka Doesn't Adopt Hybrid Storage

Kafka's consumption model relies on "partition = consumption unit": consumers maintain offsets directly on partition logs, zero-copy transfer (sendfile) by segment files — log is index. RocketMQ also uses queue as consumption unit but decouples "storage unit" from "consumption unit" — storage pursues write extreme, index补齐 read semantics. Neither is absolutely superior; topic scale and read-amplification tolerance decide .

Write Path: Four putMessage Optimizations

2.1 From Message to Disk: mmap & PageCache

CommitLog writes via memory mapping (mmap): file mapped into process address space, write becomes memory write, persistence delegated to kernel async flush — request path latency shifts from "disk IO" to "PageCache write", the physical reason async flush mode achieves sub-millisecond send latency. Four optimizations around this path, each "moves uncertainty before write":

Pre-allocation (AllocateMappedFileService background creates next 1GB file early)

Pre-warming (warmMappedFile sequentially touches all pages + writes zero, moves page faults before write)

Off-heap staging (transientStorePool, write goes through DirectBuffer, fsync done by background, write path doesn't contend with flush lock)

Sequential append (write point always at file end, disk-head/flash friendly)

2.2 Why Sync Flush Must Group Commit

In SYNC_FLUSH mode, disk IO returns to request path — single fsync takes milliseconds, serial throughput collapses. GroupCommitService solution: group commit — batch concurrent requests, flush thread does one fsync covering whole batch, then wakes all — merges N disk IOs into 1. Same idea as MySQL redo log group commit and Kafka ISR batch flush: when synchronous wait unavoidable, amortize wait across a batch . Sync flush P99 determined by fsync latency, so financial prerequisite is always good disks (NVMe).

Operational detail: group commit wait queue depth caps concurrency — requests arriving within batch window wait together, outside queue for next round. Sync flush throughput curve is "step-shaped": low concurrency latency = one fsync; concurrency rises throughput steps up, latency flat (shared within batch); higher concurrency queues and latency rises. Stress test must scan concurrency tiers to find step inflection — inflection = capacity red line, review at 70% of inflection.

Read Path: ConsumeQueue Two-Level Jump

3.1 Fixed-Length Entry: 20-Byte Arithmetic Positioning

ConsumeQueue is main consumption index: one file sequence per queue, each message maps to fixed 20-byte entry — CommitLog physical offset (8B) + message size (4B) + tag hash (8B). Fixed length is key: offset to file position is arithmetic (offset / 20 × 20), no parsing, no search, single pread positions. vs Kafka sparse index (variable-length + binary search), RocketMQ uses dense entries for O(1) locate — entries occupy more space but lookup path shorter. Hot queue index files fully resident in page cache, index reads near zero CPU.

Tag filtering division worth memorizing: broker only does hash pre-filter — hash collisions cause false positives (different tags may share hash), exact filtering done on consumer side . So subscription expressions (SQL92 or tag strings) must not assume broker filters cleanly — consumer logic field validation cannot be omitted. Tag filter misbehavior symptom: "consumed unwanted messages", root cause 80% hash collision mistaken for exact match.

3.2 GetMessage: Complete Read Path for One Consume

Consume pull read path in three steps: ConsumeQueue locate entry → CommitLog direct read by offset → client exact filter returns . Hot data all hits page cache: index sequential read + CommitLog small-range random read (adjacent message offsets have locality). This explains a production phenomenon: why backlog replay is slow — replay reads "already evicted from page cache" old data, every read is real disk IO, and replay reads pollute page cache, evicting online hot data. So rate-limiting replay isn't stinginess, it's protecting online page cache.

Read path performance tiers mental map: Tier 1 all in-memory (index page cache hit + CommitLog page cache hit) microseconds; Tier 2 index hit CommitLog miss (milliseconds, one disk read); Tier 3 all miss (milliseconds + page cache pollution side effect) . Monitor read latency against these three tiers: latency jump from microseconds to milliseconds signals "hot window exceeds memory" — adding memory cheaper than disk and immediate effect.

Read path also couples with memory budget: page cache hit rate depends on ratio of "hot window size" to "available memory" . Hot window = active queue count × data volume corresponding to consumption rate; memory insufficient triggers kernel LRU eviction, hit rate drops, disk reads rise, latency climbs. Capacity review gives broker memory not "JVM heap bigger better" — reserve half for PageCache is message middleware machine common sense , must write into machine spec standard.

IndexFile: Key & Time Query Index

ConsumeQueue only serves "sequential consume by queue"; ops needs "query by message key" and "query by time range" — IndexFile's job (message trace, reconciliation queries use it). Classic hash index structure: 5M hash slots + 20M index entries, chaining for collisions , entry stores key hash, CommitLog offset, timestamp. Files roll by time window (default 1 hour), expire with file deletion.

Two engineering points: First , async built (dispatch service generates alongside), index lags write — query by key for just-sent message may miss, this is design behavior not bug. Second , 20M hash slots per file limit; long collision chains degrade query — high-cardinality keys (order IDs) fine, but don't use low-cardinality keys like user ID (long chains, semantically returns many) — message key design principle: "business unique key", aligned with consumption idempotency deduplication key (closes loop from earlier article).

Message key practice checklist: queryable (reconciliation, support tickets locate by it), deduplicable (consumption idempotency uses it), aggregatable (monitoring watches its distribution for skew) — one key three uses, all three reviewed at design. Anti-patterns: timestamp as key (cannot deduplicate), auto-increment ID as key (no business meaning, query reveals nothing). Wrong key design forces rework on trace query and idempotency — cheapest design decision, most frequent rework.

Ops reminder: IndexFile is the only "optional" index — clusters not needing key query can disable (message trace becomes unavailable), saving dispatch thread CPU and disk. But most teams keep it because "did this message actually get delivered where" is hard requirement in reconciliation/support — disabling saves pennies, loses debuggability. Only evaluate disabling if independent reconciliation system exists.

Flush & Replication: Two Independent Accounts

5.1 Two Flush Services Trade-offs

Flush and replication are two independent reliability lines: flush guarantees "local durability" (power loss no loss), replication guarantees "machine-level redundancy" (crash no loss) . Four combos, common two: async flush + sync replication (most business balance: local crash loses last window, machine crash no loss); sync flush + sync replication (financial). Lesson from earlier incident 3 mechanized here: any combo item downgraded breaks end-to-end promise — reliability review must align four configs (flushDiskType / brokerRole / wait replication mode), not just one. Review each: "if this item downgrades, can business accept losing recent window?" — combos with no answer don't go live.

Wait replication modes: SYNC_REPLICATION requires master wait for slave ack before returning success to producer — replication latency directly enters send P99. Slow slave (bad disk, long GC, network jitter) drags whole group send performance, mirror of "slow broker avoidance" at replication layer: master or slave slow, sender must sense and avoid. Sync replication health = slave health , monitoring slave replication lag and backlog is mandatory broker patrol item.

5.2 OS_PAGECACHE_BUSY: Spike Mechanism Full Picture

Incident 2 mechanism expanded: all writes share PageCache, while fsync (flush), replication thread file reads, deletion thread file cleanup all active on PageCache . When a write waits page cache lock > osPageCacheBusyTimeOutMills (default 1s), broker returns OS_PAGECACHE_BUSY. Not equal to disk broken — mostly transient superposition of three activities: dirty page backlog (write rate spike), deletion window hits peak, co-located tasks steal IO. Troubleshooting order: first check disk watermark & deletion window (capacity account), then IO await & dirty pages (co-location contention), last suspect hardware.

Capacity Formula (Write into Review Template)

CommitLog usage = avg write rate × retention hours; Total disk = CommitLog × 1.4 (index & redundancy overhead); Alert line 70%, deletion line 75% (ratio), reject line 85% (max). Three watermarks = three gates: alert = human reaction time, deletion = machine self-rescue time, reject = final correctness protection — any gate triggered means previous gate didn't respond .

Expiration Deletion & Clean Files: Disk Self-Healing

Deletion thread scans every 10s, dual triggers: file retention time (fileReservedTime, default 72h) expires; or disk usage exceeds ratio (default 75%) . Delete order: CommitLog first then corresponding index files; before delete wait refcount zero (actively read/write segments skipped), destroy rate limited (destroyInterval default 100ms per file) — violent deletion hurts IO, also cause of PageCache busy spikes (incident 2 trigger).

Freed 1GB space not returned to FS, segment file renamed for reuse (clean files) : avoids frequent file creation handle/inode jitter, retains pre-allocated contiguous disk blocks. Paired mmap pre-warming moves page faults before write — both details jointly guarantee "smooth write latency curve". Monitor three indicators: commitlog file count fluctuation (abnormal growth = write spike or deletion stall), deletion rate, cleanImmediately trigger count (emergency watermark deletion counter) — three eyes on capacity account.

Retention adjustment asymmetric risk: increasing retention safe (stores more data), decreasing dangerous (data being replayed may be deleted early) . Disk pressure tempts "reduce retention to save watermark", but if consumer group replaying 48h-old messages and retention changed to 24h — replay halfway data deleted, consumer offset points to deleted file, forced to skip or replay. Correct posture: watermark pressure first expand or clean non-message data, retention is business commitment, change requires business sign-off.

Backlog = Storage Debt (Incident 3 Mechanized)

Every backlogged message occupies CommitLog retention quota — backlog volume × message size directly eats disk; backlogged queues also slow recovery load (restart window). So "backlog governance" not just consumer side: set broker backlog upper-limit alerts (dual gauge: queue lag + disk usage), large-backlog brokers no planned restarts — drain traffic, failover, let low-debt machines recover first. Backlog and disk watermark coupled risk: backlog consumes retention headroom, watermark deletion starts eating "data reserved for replay" — end of uncontrolled backlog often "replay impossible", both lose.

Storage Layer Reverse Constraints: Parameters Decided by Storage

Many behaviors from earlier articles ultimately constrained by storage layer. Consolidated mapping:

Send latency floor decided by flush mode (async sub-ms, sync by fsync P99)

Max message 4MB by CommitLog single-record design limit (immutable, don't fight)

Replay window by file retention (same window two faces with offset retention)

Consume replay speed by page cache hit rate (old data = real disk IO)

Backlog capacity capped by disk capacity + recovery load time. Troubleshooting "why param tuning ineffective" first ask: is its ceiling in storage layer?

Explains why RocketMQ tuning docs emphasize disk: storage engine optimized CPU work (serialization, lookup) to extreme, remaining bottlenecks almost all IO — disk sequential write bandwidth decides write ceiling, random read ability decides replay/cold read experience, page cache size decides hot data hit rate. Selection phase giving broker best disks worth more than any param tuning later.

Storage layer "hidden contract": disk IO isolation . Co-located machines (broker + other services share host), neighbor IO spikes directly become this broker's busy spikes — PageCache and block device queues shared. Production standard either dedicated machines (recommended) or cgroup IO isolation with verified effect — "isolated but not verified" equals no isolation, incident 2 co-location theft exactly this leak. Machine spec review must include "IO dedicated or verified isolated" as entry criterion.

IO isolation verification runnable version: use fio at business low peak to benchmark target disk (sequential write + 4K random read two sets), simultaneously let neighbor service saturate its IO quota — broker write latency degradation <10% passes isolation, exceed revert to dedicated. Ten-minute verification cheaper by two orders of magnitude than post-launch spike chasing.

Production Practice: Storage Config & Health Check

8.1 Broker Storage Baseline Config

Baseline directly copy-paste deployable (each item annotated):

# ==== Flush & Replication (Reliability Combo) ====
flushDiskType=ASYNC_FLUSH  # Financial use SYNC
brokerRole=SYNC_REPLICATION # At least sync replication

# ==== Disk Watermark Three Gates ====
diskMaxUsedSpaceRatio=75    # Exceed starts deleting old files
# Reject redline default 85 (diskFull config)
# Alert line self-built: 70% into monitoring

# ==== Retention & Cleanup ====
fileReservedTime=72         # File retention hours
deleteWhen=4                # Daily deletion hour
destroyInterval=100         # Delete interval (ms)

# ==== Write Optimizations ====
transientStorePoolEnable=true  # Off-heap staging
warmMapedFileEnable=true       # File pre-warm
sendMessageThreadPoolNums=32   # Write threads

# ==== Single & Batch Limits ====
maxMessageSize=4194304      # 4MB, don't increase

Three disciplines beyond config: deletion window (deleteWhen 4AM) staggered from business peak — night-peak businesses must shift window; retention cross-checked consistent with offset retention (consumer 3.2 window is this); transientStorePool off-heap memory counted in container memory budget (JVM memory account external continuation, don't let off-heap staging OOM container).

Monitoring config adds three actionable metric definitions: write latency percentiles per-broker P95/P99 separate alerts (spikes are busy precursors); PageCache hit rate approximated by "physical disk reads / total reads" (drops below threshold = hot window exceeds memory); deletion stall detected by residual of "watermark rise - write increment" (positive residual = deletion not keeping up) — all three need no broker source changes, composable from existing metrics.

Storage config & JVM config boundary has "shared dispute zone" — direct memory vs page cache who eats whose memory. Mechanism clarified: transientStorePool uses JVM off-heap (DirectBuffer, governed by MaxDirectMemorySize); PageCache is kernel's, uses machine remaining memory (unrelated to JVM) . So container memory = heap + off-heap (incl transientStorePool) + metaspace/thread stacks + PageCache headroom — four segments separate accounts, don't put PageCache into JVM params (not JVM governed). This accounting appears repeatedly in JVM series 02 & 10 container trilogy, both sides aligned logic fully self-consistent.

8.2 Storage Health Checklist

Pre-launch and patrol each pass eight items: ① capacity formula calculated with growth headroom; ② three watermarks (70/75/85) all have monitoring alerts; ③ deletion window staggered from business peak; ④ retention cross-checked with offset retention; ⑤ flush/replication combo aligned with business reliability tier; ⑥ transientStorePool memory in budget; ⑦ backlog upper-limit alerts (lag + disk dual gauge); ⑧ large-backlog broker restart plan (drain + master-slave failover sequence). Items ①②④ directly correspond to three incidents — all three caught pre-launch by this checklist.

8.3 On-Call Playbook: Three Storage Alert Handling

OS_PAGECACHE_BUSY : first check disk watermark & deletion window (capacity account), then IO await & dirty pages (co-location contention), last suspect hardware; repeated busy short window treat as degradation (drain traffic).

Disk watermark alert : 70% warn calculate growth rate project hit time, pre-expand — don't gamble deletion thread can hold ; 85% reject already incident, first expand or clean watermark restore write, then postmortem capacity account.

Deletion stall (file count abnormal growth) : check refcount (any consumer stuck holding old files), deletion thread logs, disk IO health — deletion stall turns "expiration deletion" into "watermark reject" prelude.

Core Source Code: Four Key Implementations

1. CommitLog.putMessage Main Write Flow

What request path actually does:

public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
  // 1. State & length check
  if (!this.defaultMessageStore.isRunning()) return fastFail;
  // 2. Get a mapped file (pre-allocated)
  MappedFile mappedFile = mappedFileQueue.getLastMappedFile();
  // 3. Append write (mmap memory write)
  result = mappedFile.appendMessage(msg, cb);
  if (APPEND_OK == result.getStatus()) {
    // 4. Wake flush & dispatch
    handleDiskFlush(result, msg);
    handleHA(result, msg);     // Replication
    // Dispatch service async builds index
  }
  return putMessageResult;
}

2. DefaultMessageStore.getMessage Two-Level Jump

Complete read path implementation:

public GetMessageResult getMessage(String group, String topic,
    int queueId, long offset, int maxMsgNum, MessageFilter filter) {
  // 1. Get ConsumeQueue (queue granularity index)
  ConsumeQueue cq = findConsumeQueue(topic, queueId);
  if (cq == null) return emptyResult;
  // 2. Read entries from offset (fixed-length arithmetic locate)
  SelectMappedBufferResult cqb = cq.getIndexBuffer(offset);
  // 3. Per entry jump CommitLog read message body
  for (each entry: offset + size + tagHash) {
    if (filter matches tagHash) {
      SelectMappedBufferResult msg = commitLog.getData(offset, size);
      result.add(msg);  // Client exact filter again
    }
  }
  return result;
}

3. GroupCommitService Group Commit

Sync flush throughput savior:

// Each request enters queue: batch
public void putRequest(GroupCommitRequest request) {
  this.requestsWrite.add(request);
  // Wake flush thread
}

// Flush thread main loop
public void run() {
  while (!isStopped()) {
    // 1. Swap read/write queues (lock-free batching)
    swapRequests();
    // 2. Wait for nextOffset align: one flush
    for (req : batch) {
      flushOK = mappedFile.commit(req.getNextOffset());
      req.wakeupCustomer(flushOK);
    }
  }
}

4. Watermark & Retention Deletion Judgment

Disk self-heal trigger logic:

private double diskRatio() {
  // CommitLog partition usage
  return OperatingSystemMX.getDiskRatio();
}

public void cleanFilesByWatermark() {
  double ratio = diskRatio();
  if (ratio > diskMaxUsedSpaceRatio) {
    // Exceeds 75%: delete oldest first
    // cleanImmediately: exceed 85% continuous delete
    // until watermark falls back
    deleteExpiredFiles(immediateMode);
  } else if (file expired fileReservedTime) {
    deleteExpiredFiles(normalMode);
  }
}

Deletion-consumption coupling detail: offset validity check depends on file existence — consumer group offset pointing to segment already deleted (retention too short or backlog too long), broker treats as offset out-of-bounds, restarts from min or max offset (per config). This is mechanism root of "reduce retention causes consumer replay or skip" — retention defines boundary of all consumer group offset validity, change requires business sign-off (covered in section 6).

Source Code Reading Methodology

putMessage = "one sequential write + two wakeups", getMessage = "one index read + N CommitLog reads", group commit = "one batch one fsync", deletion judgment = "retention + watermark dual trigger". Four segments connected, storage engine behavior boundaries fully visible — all send/consume odd phenomena find physical explanation in these four.

Each segment grab one core variable: write grab mappedFile (how file obtained), read grab offset (how position calculated), flush grab batch (how batch assembled), delete grab refcount (who still using this file). Grab right variable, 40-line source read in 5 minutes; grab wrong, 2 hours still surface-level . This "one core variable per segment" method applies to later transaction, master-slave, tuning source code.

Seven Accounts: Storage Engine Real Costs

Write Amplification Account : Hybrid storage trades ConsumeQueue write amplification for CommitLog sequential write — entry overhead ~20B/msg, plus IndexFile ~10%; disk budget 1.4x factor is index tax.

PageCache Account : PageCache is write buffer and fsync/replication/deletion arena — busy spikes root cause often here; cache hit rate decides replay experience. Give broker machine enough page cache headroom (typically half memory to PageCache).

Capacity Account : Write rate × retention = CommitLog, Disk = CommitLog × 1.4; three watermarks three gates — any gate triggered means previous gate didn't respond. Capacity formula into review template.

Backlog Account : Backlog is debt on storage: eats disk retention, slows restart recovery, replay pollutes page cache — backlog upper-limit alert is storage alert, not just consumer alert.

Sync Flush Account : Group commit merges N fsyncs into one, but P99 still disk-decided — financial prerequisite is NVMe, not params.

Restart Window Account : Recovery time proportional to queue count × backlog depth — large-backlog broker planned restart must drain traffic first; recovery window hidden item in capacity review.

Deletion Stall Account : Deletion relies on "refcount zero" — one stuck consumer (holding old file) can prevent segment deletion forever, watermark pushed to reject. Deletion stall triage: which file not deleted (broker logs), who holds it (read/write state), is consumer stuck (hang or old bug) — "deletion thread normal but watermark still rising" is this account's signal . Version upgrades include related bugfixes as routine.

Index Account : Fixed-length entries for O(1) locate, hash index for key query — both indexes "async built": index lagging write is design behavior. Query by key for just-sent message misses, don't treat as bug.

Replica Sync Account : Sync replication makes slave disk/network directly enter master send P99 — "master fast slave slow" cluster more dangerous than "both slow": slow slave drags fast master to same baseline. So slave specs cannot shrink (same or slightly lower), slave patrol items same as master — replication chain performance account settled by slowest node . Explains why master-slave clusters stress "homogeneous deployment".

Fragmentation & Format Account : Clean file reuse avoids file fragmentation, but disk block allocation still managed by FS — long-running brokers no manual defrag needed (sequential write naturally spreads), but disk replacement or expansion requires capacity balancing not defrag : RocketMQ has no built-in inter-broker data migration (relies on master-slave re-sync), correct expansion posture "new broker joins cluster takes new writes" — old data distribution unchanged. Disk expansion planning must be one-shot, post-hoc add disks only amortize new writes.

Expand "correct expansion posture": new broker taking new writes depends on two things — new topic queues land on new broker, or manual mqadmin expand queue count to balance new queues onto new machines; old queue positions unchanged (migration requires master-slave re-sync, high cost/risk). So "new machine added, does write actually go there" must verify queue distribution — just adding machines without moving queues is invalid expansion, cluster version of "queue count less than instance count causes idle" from article 01.

20 Interview Questions (with Answers)

Q1–Q20 cover: CommitLog hybrid storage problem & cost; Kafka vs RocketMQ log model; CommitLog write path optimizations; ConsumeQueue entry structure & fixed-length significance; Tag filter two-layer design; Complete consume read path & backlog replay slowness; IndexFile structure & purpose; Flush vs replication responsibilities & common combos; Why sync flush needs group commit; OS_PAGECACHE_BUSY mechanism & troubleshooting order; Three watermark relationships; Expiration deletion triggers & protections; Clean file reuse & design rationale; Why broker restart slow; Why maxMessageSize not recommended larger; transientStorePool role & cost; Storage layer "reverse constraints"; Storage health checklist key items; Storage monitoring metrics; One-line summary of storage mechanisms.

One-Page Cheat Sheet

Storage Engine Nine Sentences: ① Write path single bridge: all topics share CommitLog, throughput decoupled from topic count; ② Read path two-level jump: 20-byte fixed entry arithmetic locate; ③ Broker coarse filter client exact filter: tag hash collision may false pass; ④ Flush manages local, replication manages machine: two accounts independent review; ⑤ Sync flush relies on group commit: P99 disk-decided, buy good disks first; ⑥ Busy not disk broken: first check capacity account & deletion window; ⑦ Three watermarks three gates: 70 alert 75 delete 85 reject; ⑧ Backlog is storage debt: eats disk, drags restart; ⑨ Replay rate-limited protects page cache — old data is real disk IO.

Summary & Next Episode Preview

Storage engine mechanisms condense to three sentences — turn random into sequential (hybrid storage lets thousand topics walk one write stream), turn synchronous into asynchronous (group commit, pre-allocation, pre-warming, async index — move everything possible out of request path), calculate accounts clean (retention, watermarks, backlog, recovery window — four accounts all have formulas & alerts). Send/consume behaviors from previous two articles now all have physical explanations — mechanism is source of judgment most thoroughly embodied at storage layer.

Cross-article memory anchor: Send article "fault avoidance" solves "can't write to good machine", this article "three watermark gates" solves "what if disk full", Consume article "offset closure" solves "where read counts as safe" — three articles together = "message life on disk": arrive (write path), settle (storage & index), leave (consume & delete). Any storage problem locatable to a stage on this lifecycle — stage located, tools & playbooks auto-match.

Next article "Reliability & Transaction Messages" enters message durability core: Message reliability three-stage model (send/storage/consume each own segment), Transaction message half-message & check-back mechanism, and complete solution for "local transaction + message send" atomicity — welds shut the message loss chain from Article 01 Incident 3.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

capacity planningReplicationRocketMQPageCacheSource CodeDisk WatermarkGroup CommitIncident AnalysisBacklogMessage StorageCommitLogConsumeQueueIndexFileFlush Mechanism

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion