跪拜 Guibai
← Back to the summary

100K QPS Order System: The Cache, ES, and MQ Gauntlet — Lessons from a Live Meltdown

Last year's big sale, our order center peaked at 100,000 QPS. ES deep pagination blew up the coordinator node memory, MQ backlogged 4.8 million messages, points were delayed, and the customer service group was on fire all night. This article consolidates the complete solution we settled on after that firefighting: how multi-level caching carries reads, how ES searches don't drag things down, and how MQ backlogs are caught up. It's suited for those working on high-concurrency transaction systems, or preparing for interviews.

1. First Do the Math, Then Talk Architecture

In real development we often see a situation: people immediately name components — Redis, ES, RocketMQ — but can't say which layer actually blocks the traffic. Architecture without estimation is hooliganism. Ask three questions first, and the answers narrow things by half:

First calculate the capacity:

Metric Estimate Conclusion
Order detail reads 100k QPS At 99% cache hit rate, DB fallback is only ~1k QPS
Hot keys Top 1000 products/stores account for 60% traffic Must use local cache + hot key detection
Order writes 20k QPS Shard 16 DBs × 64 tables (or user_id % 1024), single table <200 QPS
ES writes 20k TPS peak Must use bulk + routing + async sync, forbid sync dual-write
MQ peak backlog A downstream blip can stack 5M+ Needs pre-planned catch-up, not firefighting

The whole chain looks like this:

image.png

One sentence: MySQL is the source of truth, Redis and ES are derived views, MQ is the event bus. Reads rely on layered cache, searches rely on ES wide table, writes rely on Outbox+MQ for eventual consistency. All links unify around orderId + version + eventId for consistency, idempotency, and reconciliation.

Otherwise the faster the cache, the more async ES, the more MQ can shave peaks, the faster dirty data spreads. That's the feeling after the deepest pit I've stepped in.

Layering goal is not a vague "99% hit rate" but how much each layer actually blocks:

Layer Carrier TTL/Capacity Single latency Target hit Responsibility
L0 Nginx/gateway local cache 1s Very fast Flash-sale instantaneous duplicate requests Optional, blocks pulses
L1 Caffeine in-process 3–30s, tens of thousands of keys <0.1ms 40%–80% Resists hot spots, skew
L2 Redis Cluster 30min±random, GB–TB 1–3ms 95%+ Cross-instance sharing, handles most reads
L3 MySQL sharded — 5–50ms <1%–3% Only source of truth, only miss and strong-consistency reads, must be rate limited

A single Caffeine instance can handle 500k+ QPS, Redis single shard 80–100k, 16 shards enough. ES scales independently by query volume. The key isn't "using Redis" but that the DB only gets misses and strong-consistency reads.

2. Multi-level Cache: Block Read Traffic Before the Database

2.1 Why Add a Local Cache in Front of Redis

Redis is still one network round trip plus serialization, 1–3ms; Caffeine is one in-process ConcurrentHashMap read, <0.1ms, one to two orders of magnitude difference.

But the real killer is hot keys. A viral product can account for 80% of the site's traffic. Redis Cluster routes by key hash, and those requests all hit the same shard. Adding cluster nodes doesn't help because the hot spot still lands on the same slot; the shard's CPU or NIC saturates first.

So the first priority isn't "optimize Redis" but intercepting hot requests before they reach Redis. 100k QPS all to Redis: single-shard pressure and network round trips are unbearable. Very hot keys are blocked locally; Redis only handles scattered traffic.

2.2 L1 Is Special Forces, Not a Standing Army

Many people build multi-level cache by stuffing everything into Caffeine, ending up with low L1 hit rate, high GC pressure, and a wider consistency scope. My practice is to only let "worthy" data in:

Technical highlight: L1 only holds hot candidates. Use an acceptable few-seconds inconsistency window to exchange for 90% of Redis traffic. In that local cache window the user may see old status, so for high-frequency self-check fields like order status go direct to Redis; local cache only holds latency-tolerant data like product snapshots, store names. Layered consistency must be graded by field, not one-size-fits-all.

Caffeine has two expiry policies often confused: expireAfterWrite counts from write time, expireAfterAccess from last access. Hot keys are always being accessed; with the latter they may never expire, and the dirty-data window runs wild. So for L1 I generally use expireAfterWrite.

There's also a more worry-free combo: refreshAfterWrite + expireAfterWrite. The former asynchronously refreshes after expiry, letting requests read old values without blocking; the latter is a physical expiry fallback. Reading an old value is better than reading a blocked value — that's the first principle of cache design.

private final Cache<Long, OrderCacheDTO> localCache = Caffeine.newBuilder()
        .maximumSize(20_000)                       // upper bound, prevent JVM OOM
        .expireAfterWrite(10, TimeUnit.MINUTES)    // fallback expiry
        .refreshAfterWrite(1, TimeUnit.MINUTES)    // async refresh, very high hit rate
        .recordStats()
        .build(this::loadFromL2);                  // on miss auto-source

2.3 Read Path Core Code

This is an integrated version I iterated in production, sewing together Bloom filter, null sentinel, logical expiry, single-flight rebuild, random TTL:

@Service
public class OrderCacheService {

    private static final String KEY = "order:";
    private static final String NULL = "__NULL__";          // null sentinel, prevent penetration

    // L1: small capacity, very short TTL, only holds hot spots
    private final Cache<String, OrderDTO> l1 = Caffeine.newBuilder()
            .maximumSize(20_000)
            .expireAfterWrite(Duration.ofSeconds(3))
            .recordStats()
            .build();

    private final StringRedisTemplate redis;
    private final RedissonClient redisson;
    private final OrderMapper orderMapper;
    private final RBloomFilter<String> bloom;               // pre-warm existing order numbers at startup
    private final ExecutorService rebuildPool = Executors.newFixedThreadPool(8);

    /** logical expiry wrapper: physical TTL separated from logical TTL */
    record Wrap<T>(T data, long expireAt) {}

    public OrderDTO getOrder(String orderId) {
        // 1) L1 hit returns directly, hot traffic is eaten here
        OrderDTO v = l1.getIfPresent(orderId);
        if (v != null) return v;

        // 2) Bloom filter intercepts illegal orderId
        if (!bloom.contains(orderId)) return null;

        String key = KEY + orderId;
        String json;
        try {
            json = redis.opsForValue().get(key);
        } catch (Exception e) {
            // Redis exception doesn't break the flow; degrade to rate-limited DB fallback
            return loadFromDbWithSentinel(orderId);
        }

        if (NULL.equals(json)) return null;                 // null cache hit
        if (json == null) return rebuild(orderId, true);    // L2 miss: short wait to rebuild

        Wrap<OrderDTO> w = parse(json);
        l1.put(orderId, w.data());
        if (w.expireAt() > System.currentTimeMillis()) {
            return w.data();
        }
        // 3) logical expiry: return old value to survive, background single-flight rebuild
        rebuildPool.execute(() -> rebuild(orderId, false));
        return w.data();
    }

    private OrderDTO rebuild(String orderId, boolean await) {
        String key = KEY + orderId;
        RLock lock = redisson.getLock("lock:order:" + orderId); // lock granularity to single orderId
        boolean locked = false;
        try {
            locked = lock.tryLock(await ? 100 : 0, 5, TimeUnit.SECONDS);
            if (!locked) {
                // Can't get lock: briefly spin-read cache, if still nothing return degraded value, never hit DB
                sleep(50);
                OrderDTO cached = l1.getIfPresent(orderId);
                return cached != null ? cached : staleFromRedis(orderId);
            }
            // double-check to prevent duplicate DB query inside lock
            String json = redis.opsForValue().get(key);
            if (json != null && !NULL.equals(json) && !expired(json)) {
                return fillAndReturn(orderId, json);
            }
            OrderDTO db = orderMapper.selectById(orderId);
            if (db == null) {
                // cache null too, short TTL + random jitter
                redis.opsForValue().set(key, NULL, randomTtl(60, 30), TimeUnit.SECONDS);
                return null;
            }
            Wrap<OrderDTO> fresh = new Wrap<>(db, System.currentTimeMillis() + 60_000);
            // data logically expires in 60s, physical TTL 10min + random, prevent avalanche
            redis.opsForValue().set(key, toJson(fresh),
                    10 + ThreadLocalRandom.current().nextInt(5), TimeUnit.MINUTES);
            l1.put(orderId, db);
            return db;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return staleFromRedis(orderId);
        } finally {
            if (locked && lock.isHeldByCurrentThread()) lock.unlock();
        }
    }
}

A few details worth mentioning separately:

2.4 Penetration, Breakdown, Avalanche: Fill Three Pits at Once

Problem Trigger Solution Key parameters
Cache penetration Query non-existent order number, every hit goes to DB Parameter validation + Bloom filter + null short cache False positive 0.1%–1%, null TTL 30–60s
Cache breakdown Hot key expires, concurrent all fall back Single-key mutex lock + double-check / logical expiry + async rebuild Lock granularity orderId, wait 50–100ms
Cache avalanche Many keys expire at once / Redis down TTL random jitter ±20% + multi-level fallback + cluster HA + rate limiting degradation Random 0–300s

Two Bloom filter options are enough:

// Guava: in-process, for single-machine or startup warm-up
BloomFilter<String> bf = BloomFilter.create(
        Funnels.stringFunnel(Charset.defaultCharset()),
        10_000_000, 0.001);   // expected 10M, false positive 0.1%

// Redisson: distributed share, for multi-instance
RBloomFilter<String> bf = redisson.getBloomFilter("order:bf");
bf.tryInit(100_000_000L, 0.01);   // 100M, false positive 1%, pre-warm existing order numbers at startup

Breakdown protection has three routes, choose by scenario:

Scheme Principle Advantage Cost Suitable
Distributed lock + double-check Same key only one thread goes to source, others spin Good consistency, intuitive implementation Waiting threads have latency Ordinary orders, strong-consistency preference
Logical expiry (stale-while-revalidate) Data never physically expires; expiry time written in value; on expiry return old value + async rebuild Users never wait on DB, highest availability Brief old-value read Flash-sale products, store pages, super hot keys
refreshAfterWrite async refresh Caffeine refreshes in background after expiry, requests read old value without blocking Least code, high hit rate Only effective at L1 Local cache layer

I stepped on this pit before: I put logical expiry on order details by default, and the business complained "why is status still old?". Later I changed it to only use logical expiry for super hot keys like flash-sale products and store pages, trading availability for consistency, and explicitly told the business "you might read data 3 seconds old". Orders are data with strong-consistency preference; don't apply availability schemes as default.

Beyond TTL jitter, two things must be done for avalanche: Redis cluster isolation by business (orders/inventory/cart on different clusters, so one business doesn't saturate and drag the whole site), and Sentinel for DB fallback with concurrency rate limiting + circuit breaker degradation, returning cached old values or fallback pages. If Redis truly dies, queries go through fallback interface, querying only core status, not large objects.

2.5 Hot Keys and Big Keys: Redis Cluster Isn't a Panacea

Beyond local cache, hot key governance also includes key replication to spread: order:{id} replicated to order:{id}:v1/v2, or add random suffix, split by user/store dimension, and randomly pick one replica on read. For write scenarios split key prefixes.

Big keys also kill. An order with too many items, logistics traces — network jitter and cluster timeouts follow. Split order list keys, split big hash fields, forbid KEYS, HGETALL big collections, use SCAN instead, monitor slowlog.

Inventory hot spots have a clever design: segmented inventory. Single SKU hot spot split into stock:{sku}:{seg} segments, with Lua atomic pre-deduction; the write-chain section later posts the code.

2.6 Consistency: Cache Is Deleted, Not Updated

Here's the conclusion: Update DB first, then delete cache, with delayed double-delete as the fallback for concurrent dirty reads.

Why not "delete cache first, then update DB"? After deleting, the concurrent read before the DB update re-fills the old value, dirty until TTL expires. Why not "update cache"? Deleting is easier to guarantee eventual consistency than updating; concurrent writes on update easily let old values overwrite new ones.

Bare Cache-Aside has a classic hole: thread A updates DB then deletes cache; meanwhile thread B reads old value and re-fills. So the production answer is double-delete + binlog fallback:

image.png

@Transactional
public void updateOrder(OrderDTO dto) {
    orderMapper.updateById(dto);                              // 1. update DB first
    outboxMapper.insert(Outbox.of("ORDER_UPDATE", dto));      // same DB same transaction, event 100% not lost

    redis.delete(KEY + dto.getOrderId());                     // 2. delete L2
    redis.convertAndSend("order:cache:invalidate", dto.getOrderId()); // 3. broadcast to clear L1 on all nodes

    // 4. delayed double-delete: cover the window where concurrent reads write old value back to cache
    delayExecutor.schedule(
        () -> redis.delete(KEY + dto.getOrderId()), 500, TimeUnit.MILLISECONDS);
}

// Every service instance subscribes; on receiving, invalidate local L1
@Bean
RedisMessageListenerContainer localCacheInvalidator(RedisConnectionFactory cf) {
    var c = new RedisMessageListenerContainer();
    c.setConnectionFactory(cf);
    c.addMessageListener((msg, pattern) ->
        l1.invalidate(new String(msg.getBody(), StandardCharsets.UTF_8)),
        new ChannelTopic("order:cache:invalidate"));
    return c;
}

There's a frequent follow-up question here; I'll proactively close it:

Ordinary MQ cluster consumption only clears L1 on one machine; local cache must use broadcast invalidation. Redis Pub/Sub doesn't guarantee reliable delivery — what if it's lost? TTL + reconciliation as fallback. I dare set L1 TTL at 3–30 seconds because status transitions themselves go through MQ; the consumer side triggers invalidation events, Pub/Sub just makes most instances aware within seconds. The very few that don't receive it are at most one TTL window old, and there's scheduled reconciliation compensation. No permanent local cache inconsistency is allowed; a seconds-level delay is acceptable.

Consistency scheme selection comparison:

Scheme Approach Pros Cons Suitable
Update DB then delete cache Cache-Aside basic Simple Delete failure = dirty data Non-core data
Delayed double-delete Delete → delay 500ms → delete again Covers concurrent re-fill window Delay time hard to be precise Legacy systems that can't use Canal
Binlog subscription delete cache Canal→MQ→delete cache Guaranteed delivery, decoupled, no missed deletes One extra component Production main scheme
Outbox+CDC Event and business write in same transaction Eliminates dual-write inconsistency Needs a delivery component Core transaction path

Cache value carries version/updateTime; on delete failure or message disorder, compare version to prevent old override, plus scheduled reconciliation. For strong-consistency scenarios (payment status), go direct to the primary DB, or briefly to DB; don't query cache or ES.

If this section is useful, hit follow first; the ES and MQ pitfalls later are harder, all bought with online incidents.

3. ES Search: It's a Query View, Not a Second Database

3.1 Position Right: ES Returns IDs, Details Go Back to Cache

Get this wrong and everything after is wrong. ES doesn't store authoritative data; it only keeps a searchable view. All writes are MySQL-authoritative; ES syncs asynchronously via MQ/binlog. Violate this, and sooner or later "ES shows paid, but DB says shipped" customer complaints.

In an order system, ES does only one thing:

Complex condition search -> return order ID list -> details then go to Redis/MySQL

Don't let ES handle strong-consistency queries, order-detail primary queries, or complex transactional updates. ES only "finds IDs"; details always go back to Redis — this is the most overlooked performance gate. List pages _source only fetch necessary fields, even fetchSource(false)+fetchField("orderId") to only get ID, cutting ES network IO by 90%.

Use wide table redundancy in the index: store merchant name, product title snapshot directly in the index, don't go back to MySQL on query, avoiding lots of nested/join. ES is not a database; don't join.

3.2 Index Design: Monthly Rolling, Shard Calculation, Mapping Convergence

Orders have an obvious time attribute; users default to recent orders. Monthly index order_yyyyMM, read alias orders_read/order_active; query only scans that month. Old indexes can reduce replicas, go read-only. For major version changes use alias switch and dual-write transition to avoid locking the online index.

Shard count is calculated by data volume, not guessed:

Single shard 20–50GB, total shard count ≈ data nodes ×2–3, primary shard count can't be changed after setting. A real calculation: 3M new orders/day, 3 months ≈ 270M documents, 1KB/doc ≈ 300GB; 12 shards + 1 replica is enough. Don't do 100 shards — that's a beginner's grave; too many shards means cluster metadata and query fan-out explode.

Mapping convergence principles: keyword over text when possible; exact fields use keyword or numeric types to save space; amounts use scaled_float; fields not used for query/aggregation disable index and doc_values; index size can shrink 30%–40%.

{
  "settings": {
    "number_of_shards": 12,
    "number_of_replicas": 1,
    "refresh_interval": "5s",
    "index.sort.field": ["create_time", "order_id"],
    "index.sort.order": ["desc", "desc"],
    "index.translog.durability": "async",
    "index.translog.sync_interval": "30s"
  },
  "mappings": {
    "properties": {
      "order_id":    { "type": "keyword" },
      "user_id":     { "type": "long" },
      "status":      { "type": "byte" },
      "shop_id":     { "type": "keyword" },
      "amount":      { "type": "scaled_float", "scaling_factor": 100 },
      "create_time": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||epoch_millis" },
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }
      },
      "remark":  { "type": "text", "index": false },
      "address": { "type": "text", "index": false, "doc_values": false }
    }
  }
}

Reasons for several design decisions:

3.3 Routing: Let 80% of Queries Hit One Shard

C-side "my orders" is 80% of traffic, naturally user-dimensional. Both write and query specify routing = user_id (multi-tenant use tenant_id); same user's orders land on same shard:

IndexRequest req = new IndexRequest("order_idx")
        .id(order.getOrderId())
        .routing(order.getUserId())     // query "my orders" only hits 1 shard
        .source(json, XContentType.JSON);

Gain: query fan-out drops from 24 shards to 1, coordinator merge overhead drops 1/N, P99 cut in half or more. Cost: hot big merchants/users may skew, so B-side backend queries go to a separate non-routed index, or route by time.

3.4 Write Side: Async Bulk and Refresh Trade-offs

Order status transitions are frequent; if every change refreshes in real-time, segment merge pressure kills search latency. Never let the write interface sync-write to ES; unify to MySQL → Outbox/Canal → MQ → ES Writer → Bulk.

Action Parameter Gain Cost
Increase refresh interval refresh_interval: 5s~30s Write TPS +30%–80% Search visibility latency lengthens
Batch write bulk single batch 500–1000 / 5–15MB Fewer round trips, throughput doubles Batch too big blows coordinator node; over 500 gets slower
Control replicas write-heavy set replica 1, big-sale temporarily 0 Reduce write amplification Read capability drops, must restore after
Async translog durability: async, sync_interval: 30s Reduce fsync overhead Extreme crash may lose a few unsynced data

For scenarios needing "second-level visibility" like order status, don't touch refresh_interval casually; only temporarily set -1 + replica 0 for batch imports, then change back. I've seen someone set production index refresh to 30s and users couldn't find their orders after placing them — complaints escalated.

Consumer side does micro-batch (accumulate 200ms or 500 messages) + concurrent consumption + failure exponential backoff; bulk doesn't wait for refresh; failed entries go to retry queue + dead letter, never lost:

BulkRequest bulk = new BulkRequest();
bulk.setRefreshPolicy(WriteWaitPolicy.NONE);
for (OrderEvent e : batch) {
    bulk.add(new IndexRequest("order_" + MonthUtil.of(e))
            .id(e.getOrderId())                  // docId=orderId, same id overwrite is naturally idempotent
            .routing(e.getUserId())
            .version(e.getVersion())             // external version rejects old overwrite
            .versionType(VersionType.EXTERNAL)
            .source(JSON.toJSONBytes(e), XContentType.JSON));
}
BulkResponse resp = esClient.bulk(bulk, RequestOptions.DEFAULT);
if (resp.hasFailures()) {
    retryQueue.send(failedItems(resp));          // failures go to retry queue + dead letter, scheduled reconciliation fallback
}

Supporting reconciliation job: hourly compare DB vs ES counts/sampled content (or full checksum), auto-compensate differences. ES and MySQL accept second-level to minute-level eventual consistency, but reconciliation must exist.

3.5 Query Side: Filter, Field Trimming, and the Forbidden Zones

Order search is "precision-filter-first, relevance-sort-second". Using filter correctly is more effective than tuning shard count:

3.6 Deep Pagination: Why from+size Is a Silent Killer

from=10000, size=20 means each shard returns the first 10020 hits to the coordinator node, which merges then discards the first 10000. The deeper the page, the bigger the waste; memory and network blowup is inevitable. Default from+size limit is 10000; beyond that it errors directly.

Three pagination schemes compared:

Pagination Can jump pages Deep page performance Suitable scenarios
from + size Yes Page depth worsens linearly Backend list first few pages (limit to 100 pages)
search_after + PIT No, only next Roughly constant, O(pageSize) App pull-down, order list "load more"
scroll No Low traversal cost, but long-term occupies segment resources Full export, offline batch; forbid online UI paging

search_after uses last page's last sort value as cursor. Sort key must be unique; use create_time DESC, order_id ASC composite sort, with order_id as tie-breaker to guarantee no loss or duplication.

PIT (Point in Time) solves "cursor drift" during paging: if new orders are written while paging, the same cursor's result set changes. PIT freezes a Lucene segment view at a point in time, ensuring the whole paging session sees the same snapshot. keep_alive strictly controlled, user's longest stay +1–2 minutes buffer; don't set beyond 10 minutes, otherwise old segments can't be merged and reclaimed, disk will alarm. PIT instance memory overhead is only KB-level; a single node can support thousands of active PITs.

public PageResult<OrderDoc> search(OrderQuery q, String pitId, Object[] lastSort) {
    if (pitId == null) {
        pitId = client.openPointInTime("order_idx", "2m").getId();
    }
    BoolQueryBuilder bool = QueryBuilders.boolQuery();
    bool.filter(QueryBuilders.termQuery("user_id", q.getUserId()));
    bool.filter(QueryBuilders.termsQuery("status", q.getStatusList()));
    bool.filter(QueryBuilders.rangeQuery("create_time")
            .gte(q.getStart()).lte(q.getEnd()));          // fixed boundary, not now
    if (StringUtils.hasText(q.getKeyword())) {
        bool.must(QueryBuilders.multiMatchQuery(q.getKeyword(), "title^3", "shop_name")
                .operator(Operator.AND));
    }

    SearchSourceBuilder src = new SearchSourceBuilder()
            .query(bool)
            .size(20)
            .trackTotalHits(false)
            .fetchSource(new String[]{"order_id", "status", "amount", "create_time"}, null)
            .sort("create_time", SortOrder.DESC)
            .sort("order_id", SortOrder.DESC);            // unique tie-breaker
    if (lastSort != null) src.searchAfter(lastSort);

    SearchRequest req = new SearchRequest("orders_read")
            .routing(String.valueOf(q.getUserId()))       // single-shard routing
            .source(src)
            .pointInTime(new PointInTimeBuilder(pitId).keepAlive("2m"));
    return toResult(esClient.search(req, RequestOptions.DEFAULT), pitId);
}

The corresponding DSL looks like this, can be run directly in Kibana:

GET orders_read/_search?routing=10086
{
  "size": 20,
  "track_total_hits": false,
  "_source": ["order_id", "status", "amount", "create_time"],
  "query": {
    "bool": {
      "filter": [
        { "term": { "user_id": 10086 } },
        { "term": { "status": "PAID" } },
        { "range": { "create_time": {
            "gte": "2026-06-01T00:00:00+08:00",
            "lt":  "2026-07-01T00:00:00+08:00" } } }
      ]
    }
  },
  "sort": [
    { "create_time": "desc" },
    { "order_id.keyword": "desc" }
  ],
  "search_after": [1719820800000, "ORDER_998"]
}

Real measured data before/after optimization, to give you a feel:

Query type Before After Improvement
Shallow pagination (first 10 pages) 200ms 15ms 13x
Deep pagination (page 1000) 5000ms 20ms 250x
By user query 150ms 5ms 30x
Aggregation stats 3000ms 200ms 15x
Write throughput 2000/s 15000/s 7.5x

Fast queries are designed, not tuned. Wide table + routing + filter + search_after done right, P99<100ms is a natural result.

3.7 Degradation Posture When ES Jitters

ES is not the core transaction chain; its failure must not affect order placement or details:

Order list can accept second-level latency, but transaction status strong-consistency reads can't depend on ES. When MQ backlogs, ES necessarily lags; this boundary must be aligned with business beforehand.

4. MQ Backlog Catch-up: Stop Bleeding First, Then Speed Up, Then Reconcile

4.1 Two Formulas First

The essence of backlog: production rate > consumption rate, everything else is surface.

Catch-up time T = current Lag / (consumption rate C - production rate P)
If C <= P: never catches up; must first rate-limit/degrade/expand partitions to make C > P
Effective parallel consumption threads = min(queue count, consumer instances × threads per instance)

Queue count is the ceiling. In RocketMQ cluster consumption mode, one Queue can be consumed by only one Consumer instance at a time; in Kafka, one partition by one consumer. If a Topic has only 4 Queues, scaling to 100 Consumer instances means 96 get no Queue, watching from the sidelines; consumption speed doesn't move.

A real calculation: 4 queues × 2 instances × 20 threads = only 40 concurrency. Single message 200ms → theoretical TPS only 200; production side 800/s, no backlog would be a miracle.

4.2 Diagnosis: 90% of Backlogs Are Slow Consumers

Don't add machines first; look at monitoring for diagnosis:

image.png

Look at these specific metrics: Lag continuously growing or flat? Lag concentrated in a few queues (partition imbalance)? Consumption TPS, single-message P99, thread pool queue, Rebalance count, DB slow SQL, ES bulk reject, DB connection pool, error rate. Mnemonic: who is slow, who is insufficient, who is broken.

Of the backlog incidents I've handled, 90% are slow consumers, not slow MQ. Slow SQL and synchronous RPC are the hidden throughput killers.

4.3 Minute-Level Handling SOP

Time Action Key point
0–2min Confirm production/consumption rate, partition water level Qualify, don't act blindly
2–5min Stop bleeding: non-core consumption (SMS/marketing) degrade or drop or divert to delayed Topic; downstream DB rate-limit Protect core path (inventory, state machine), first make C>P
5–10min Expand parallelism: threads 20→64 → instances up to = queue count → only then expand queue First confirm downstream DB can take it, otherwise accelerating consumption crashes the DB, more dangerous than backlog
10–30min Batch consumption + thread pool concurrency; queue insufficient use temporary Topic flood discharge; extreme cases dump to pending table Catch-up doesn't impact downstream
After Reconcile → re-supply → restore original consumer group → review rate-limit thresholds Idempotency ensures duplicate consumption harmless

Thread expansion detail: RocketMQ's consumeThreadMin and consumeThreadMax both must be changed, otherwise the thread pool won't dynamically expand. IO-intensive take cores ×4–8. Batch pull tune up consumeMessageBatchMaxSize/max.poll.records/pullBatchSize, compressing N network round trips into 1.

DefaultMQPushConsumer c = new DefaultMQPushConsumer("order_group");
c.subscribe("order_topic", "*");
c.setConsumeThreadMin(64);
c.setConsumeThreadMax(64);                 // both must be changed
c.setConsumeMessageBatchMaxSize(32);       // batch pull

Queue expansion has nuances: RocketMQ adding queue requires expanding broker; Kafka can admin.createPartitions directly, but note the brief disorder caused by hash redistribution:

public void scaleOut(String topic, int targetPartitions) {
    if (currentPartitions(topic) < targetPartitions) {
        admin.createPartitions(Map.of(topic, NewPartitions.increaseTo(targetPartitions)));
        log.warn("Partition expansion {} -> {}, note hash redistribution causing brief disorder", topic, targetPartitions);
    }
}

4.4 Temporary Topic Flood Discharge: Emergency Move When Queue Count Isn't Enough

Backlog in millions, original Topic only 4 queues, business can't wait — expanding consumers is useless. Do flood discharge diversion:

image.png

Speed-up ≈ new queue count / old queue count = 32/4 = 8x. 1M backlog: original 8 consumers × 500/s = 4000/s needed 250 seconds; expand to 32 consumers 62 seconds; temporary 64-partition Topic forwarding 31 seconds; stack batch consumption 15 seconds.

Technical highlight: the forwarding Consumer intentionally doesn't write DB, doesn't call RPC — only re-sends messages. If the forwarding stage also writes DB, the bottleneck immediately returns to the database connection pool; no matter how many partitions the new Topic has, it's useless. Catch-up stage does only "moving", with business processing fully deferred to the new Topic's consumers — that's the essence of clearing out tens of times faster.

@RocketMQMessageListener(topic = "order_topic", consumerGroup = "relay_group",
                         consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadNumber = 4)
public class RelayConsumer implements RocketMQListener<MessageExt> {

    private final RocketMQTemplate template;

    @Override
    public void onMessage(MessageExt m) {
        // pass through as is; business key KEYS must never be lost — downstream relies on it for idempotency
        // hash by orderId evenly route to multiple Queues of new Topic, ensuring same order ordering
        template.syncSend("order_topic_tmp",
            MessageBuilder.withPayload(m.getBody())
                .setKeys(m.getKeys())
                .setHeader("TAGS", m.getTags())
                .build());
    }
}

The cost must be written into the plan: ordering entirely lost (temporary Topic hash by orderId can mitigate), possible duplicate consumption (consumer must be idempotent), extra storage, temporary Topic must be cleaned and rolled back after use. The forwarding layer itself must be idempotent to avoid duplicate forwarding. Can use a separate consumer group to replay backlog data, avoiding impact on online consumption.

There's an even more brutal dump and catch-up: pull messages and directly batch insert into a pending table, moving the backlog from MQ to your own DB. MQ water level drops immediately; background thread pool replays compensation slowly per downstream capacity.

@Scheduled(fixedDelay = 30_000)
public void dumpWhenLagging() {
    long lag = mqAdmin.lag("g_order_es");
    if (lag > 30_000_000L) {
        switcher.on("DUMP_ONLY");    // consumer switches to batch insert pending_order_event
    } else if (lag < 100_000L) {
        switcher.off("DUMP_ONLY");   // after water level safe, replay pending table, resume normal
    }
}

Historical data catch-up also has a snapshot scheme: stop consumption → full export → enable binlog incremental catch-up, for data rebuild scenarios.

In extreme cases "discard" is the last resort, but only for rebuildable data: log-type, stats-type, messages rebuildable from DB can skip offsets; a "payment success" SMS 3 hours old that's overdue just return SUCCESS and discard. Order creation/payment/inventory deduction messages — not a single one can be lost; only forward and catch-up + idempotent consumption.

4.5 Batch + Concurrency + Backpressure: Catch-up Can't Kill Downstream

Catch-up consumption rate must be constrained by downstream capacity: rate=min(consumption capability, downstream capacity), using dynamic rate limiter based on downstream RT/error rate for backpressure; otherwise saving fire turns into setting fire.

@RocketMQMessageListener(topic = "order_created", consumerGroup = "point_consumer",
        consumeMode = ConsumeMode.CONCURRENTLY, batchMaxSize = 32, maxReconsumeTimes = 3)
public class PointConsumer implements RocketMQListener<List<MessageExt>> {

    private final RateLimiter limiter = RateLimiter.create(2000);  // downstream capacity 2000 TPS
    private final StringRedisTemplate redis;
    private final PointService pointService;
    private final ThreadPoolExecutor pool = new ThreadPoolExecutor(
            16, 32, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(10_000),
            new ThreadPoolExecutor.CallerRunsPolicy());   // slow down instead of OOM when pool full

    @Override
    public void onMessage(List<MessageExt> msgs) {
        // backpressure: auto slow when downstream RT P99 rises, ES 429 exponential backoff
        if (downstreamRtP99() > 200) limiter.acquire(msgs.size());

        // idempotent: batch setnx, only those grabbed are processed
        List<String> todo = msgs.stream()
                .map(m -> m.getKeys())
                .filter(id -> Boolean.TRUE.equals(redis.opsForValue()
                        .setIfAbsent("point:done:" + id, "1", Duration.ofDays(7))))
                .collect(Collectors.toList());
        if (todo.isEmpty()) return;

        try {
            pointService.batchAdd(todo);          // batch DB write, avoid per-row update
        } catch (Exception e) {
            todo.forEach(id -> redis.delete("point:done:" + id));  // release idempotent key on failure
            throw e;                              // trigger retry (exponential backoff), over limit into dead letter
        }
    }
}

ES sync consumer uses same pattern: batch + split-batch parallel write ES (single batch ≤500), idempotency via ES _id overwrite naturally resists duplicates, cheaper than building a separate idempotency table; failures go to dead letter queue for manual/scheduled compensation, never block main flow.

List<OrderMsg> valid = idempotent.filter(msgs);
Lists.partition(valid, 500).forEach(batch ->
        pool.execute(() -> syncToEs(batch)));     // CallerRunsPolicy backpressure fallback

Batch + parallel can compress single-message RT from 5ms to 0.1ms level, but only if idempotency and backpressure are in place. Without idempotency, batch replay accelerates duplicate writes to nightmare levels.

4.6 Idempotency and Ordering: The License to Speed Up

MQ delivers at-least-once; retries, rebalance, batch ack failure replay inevitably cause duplicate consumption. Order events must carry all these fields:

eventId / orderId / eventType / version / eventTime

Three lines of idempotency defense:

  1. eventId unique deduplication: Redis SETNX + DB unique index double insurance. DB idempotency table status NEW/PROCESSING/DONE; PROCESSING needs watchdog timeout reset, preventing consumer crash from leaving messages stuck forever.
  2. orderId + version prevents old events overwriting new: old version discarded, same version allowed re-entry, new version advances.
  3. State machine validation: forbid illegal status transitions; status only moves forward.
UPDATE t_order
SET status = #{targetStatus},
    version = #{version},
    update_time = NOW()
WHERE order_id = #{orderId}
  AND version < #{version}
  AND status IN
    <foreach collection="#{allowFromStatus}" item="s" open="(" separator="," close=")">
        #{s}
    </foreach>

Affected rows 0 means duplicate, stale, or illegal event; skip directly. This SQL is naturally idempotent, safer than check-then-update.

Ordering and parallelism are a natural contradiction. Same order's status transitions must hash to the same partition; within partition ordered:

producer.send(msg, (mqs, m, arg) -> {
    String orderId = (String) arg;
    int idx = Math.abs(orderId.hashCode()) % mqs.size();  // same order same queue
    return mqs.get(idx);
}, order.getOrderId());

Cost is hot orders/hot users pile up in a single queue; expanding consumers doesn't help. Three solutions:

Don't sacrifice all concurrency for global ordering. Consumer side can also use hash bucketing to achieve "different orders parallel, same order serial":

private static final int N = 64;
private final ExecutorService[] bucketExecutors = singleThreadExecutors(N);

@KafkaListener(topics = "order_event", containerFactory = "batchFactory")
public void consume(List<ConsumerRecord<String, OrderEvent>> records, Acknowledgment ack) {
    Map<Integer, List<ConsumerRecord<String, OrderEvent>>> buckets =
        records.stream().collect(Collectors.groupingBy(r -> bucket(r.key())));

    CompletableFuture.allOf(
        buckets.entrySet().stream()
            .map(e -> CompletableFuture.runAsync(
                () -> e.getValue().forEach(this::handleOne),
                bucketExecutors[e.getKey()]))
            .toArray(CompletableFuture[]::new)
    ).join();

    ack.acknowledge();   // commit only after whole batch succeeds; failure replay covered by idempotency
}

private int bucket(String orderId) {
    return Math.floorMod(orderId.hashCode(), N);
}

private void handleOne(ConsumerRecord<String, OrderEvent> r) {
    OrderEvent e = r.value();
    if (!idempotent.begin(e.eventId())) return;          // eventId dedup
    try {
        if (!versionGuard.accept(e.orderId(), e.version())) {
            idempotent.done(e.eventId());                // old version discard, same version re-entry
            return;
        }
        esBulk.upsert(e.orderId(), e.toEsDoc(), e.version());  // external version prevents disorder
        redis.delete(key(e.orderId()));
        redis.convertAndSend("order-cache-invalidate", e.orderId());
        idempotent.done(e.eventId());
    } catch (Exception ex) {
        idempotent.fail(e.eventId());                    // retry; over limit goes to DLQ
        throw new RuntimeException(ex);
    }
}

Poison messages (repeatedly failing and blocking the queue) must be isolated: maxReconsumeTimes=3 (or 8) then into dead-letter Topic, manual background retry, monitor DLQ growth rate, close loop within 24 hours. Don't let one message block a whole partition.

4.7 Not Losing Messages and Monitoring to Prevent Recurrence

Complete chain for not losing messages:

Link Scheme
Production side Transactional message / Outbox local message table + sync flush
Consumption side Manual ACK + idempotency + retry (exponential backoff) + dead-letter queue manual fallback
Ordering hash(orderId) % partition count, same order same partition
DB and cache Update DB then delete cache + Canal subscribe binlog async delete fallback
DB and ES MQ eventual consistency + scheduled reconciliation (compare count/sample checksum)

After catch-up, must prevent recurrence, otherwise next big sale is the same show:

@Component
public class MqBacklogMonitor {

    private static final long WARN_THRESHOLD = 10_000;      // 10k alarm
    private static final long CRITICAL_THRESHOLD = 100_000; // 100k trigger expansion
    private static final long BLOCK_THRESHOLD = 500_000;    // 500k degrade

    @Scheduled(fixedRate = 10_000)
    public void checkBacklog() {
        long total = consumer.getConsumerStatus().values().stream()
                .mapToLong(s -> s.getDiffTotal()).sum();
        if (total > BLOCK_THRESHOLD) {
            alarmService.sendCritical("MQ backlog over 500k, trigger degrade!");
            triggerDegrade();      // disable ES sync/stats, batch to 200
        } else if (total > CRITICAL_THRESHOLD) {
            alarmService.sendWarn("MQ backlog over 100k, trigger expansion!");
            triggerScaleUp();      // K8s HPA scales consumer Pods by lag
        } else if (total > WARN_THRESHOLD) {
            alarmService.sendInfo("MQ backlog alarm: " + total);
        }
    }
}

Supporting: Lag second-level alarm, consumption P99 monitor, K8s HPA auto-scale by lag (kubectl scale deployment order-consumer --replicas=32), rate-limit the production side, preventing another instant surge from breaking after backlog catch-up. Dead-letter queue messages offline investigation, replay compensation after fix.

5. The Hidden Fourth Question: Consistency Coupling and Safety Net Foundation

Cache, ES, MQ are not three independent components; underneath is a data flow. If an MQ message is lost, both ES and cache go stale. That's the real exam point of this coupled problem set.

5.1 Outbox: Prevent "DB Success, Message Lost"

Dual-write always inconsistent. Two classic incidents: DB commits but MQ send fails; MQ send succeeds but DB rolls back. Outbox's solution: business data and event message land in the same local transaction, then a deliverer (scheduled task or CDC) reads Outbox and sends MQ:

BEGIN;
INSERT INTO t_order(order_id, user_id, status, version, ...)
VALUES (?, ?, 'CREATED', 1, ...);

INSERT INTO t_outbox(event_id, order_id, version, payload, status)
VALUES (?, ?, 1, ?, 'NEW');
COMMIT;

No distributed transaction dependency, no acceptance of "DB success, message lost". In order placement, inventory pre-deduction can use Lua to ensure Redis atomic; segmented inventory solves hot SKU:

-- KEYS[1]=stock:{sku}:{seg}; KEYS[2]=idem:{reqToken}
-- ARGV[1]=qty; ARGV[2]=userId; ARGV[3]=ttlSeconds
local qty = tonumber(ARGV[1])

if redis.call('EXISTS', KEYS[2]) == 1 then
  return {0, 'DUPLICATE'}
end

local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left < qty then
  return {-1, 'NO_STOCK'}
end

redis.call('DECRBY', KEYS[1], qty)
redis.call('SET', KEYS[2], ARGV[2], 'EX', tonumber(ARGV[3]))
return {1, 'OK'}

Outbox avoids distributed dual-write, Lua ensures atomicity, segmented inventory solves hot spots. These three combined make the order placement main path only write DB + send event; time-consuming business fully async, avoiding order placement dragged down by downstream.

5.2 Write Path and Read Path Coupling

Write path: order status change → MySQL transaction → Outbox → MQ → cache invalidation / ES update / downstream notification.

Read path: detail via local cache → Redis → MySQL; search via ES → return orderId → Redis get detail → MySQL fallback.

Don't let ES directly return order details; reasons stated before: update latency, unsuited for strong-consistency reads, large fields slow search.

5.3 Coupled Degradation During Backlog

If ES write backlogs, the answer isn't "stop business" but:

  1. Detail page continues Redis/MySQL, unaffected.
  2. Search page allows brief delay.
  3. Admin backend degrades to precise query by order number.
  4. Critical status changes go into high-priority queue.
  5. After backlog catch-up, run reconciliation to repair ES, broadcast cache invalidation.

That's engineering: not pursuing real-time consistency at all times, but ensuring core path availability and eventual consistency with repair capability.

Summary of each object's fallback:

Object Fallback
Redis / Caffeine short TTL + event invalidation broadcast + version rejects old events
ES docId=orderId + external version + bulk retry + reconciliation
MQ orderId partition ordering + eventId idempotency + DLQ
Strong-consistency read payment/order status direct to primary DB, not ES/local cache

5.4 Reconciliation + Idempotency: The Seatbelt for All Optimizations

Someone asked: if I can only optimize one place, where? Treat cache hit rate first. 100k QPS, 90k are reads; hit rate from 95% to 99% cuts DB and ES traffic in half, making all subsequent problems lighter. Optimization should hit the layer with the most traffic, not the hardest line of code.

But if I can only do one thing for stability, I choose reconciliation + idempotency system. Cache will be inconsistent, ES will miss syncs, MQ will duplicate and lose. As long as reconciliation can find differences and idempotency can safely replay, all other optimizations can be boldly tried; without this foundation, any high-performance scheme amplifies the fault radius.

Priority order I've thought through: MQ reliability > ES deep pagination > multi-level cache. The first two cause data loss or kill search; cache problems are slow but data remains.

Any link optimization must ask: will pressure be transferred to the next link? Expanding consumers crashes DB, tuning up refresh brings complaints, logical expiry spreads old status — all are transfers.

5.5 Observability and Plan Rehearsal

Three middlewares, slow to locate problems; must have instrumentation:

Before launch, do full-chain load testing + fault injection: Redis primary down, ES single node down, MQ consumption stopped; verify degradation and catch-up plans actually run. Plans aren't written in documents; they're rehearsed.

Trade-offs must be written into design docs and signed with business: order system prioritizes consistency and no message loss; availability via multi-level degradation. Product/marketing cache prioritizes availability and performance, allows second-level dirty reads.

6. Quick Reference Table of Difficulties

Condense all pitfalls into one table with acceptance metrics, usable directly to compare against your own system:

# Technical difficulty Root cause Solution Acceptance metric
1 100k QPS hits Redis/DB hot concentration, no local blocking Caffeine blocks super hot + Redis sharding + Bloom filter + hot key detection DB peak QPS <2000
2 Hot key blows single shard Cluster hashing routing, adding nodes useless local cache + key replication spread + segmented inventory + sliding window detection single shard CPU <60%
3 Big key / slow command big set network jitter split key/field, forbid KEYS/HGETALL, SCAN instead, slowlog monitor no slow command alarm
4 Cache penetration illegal key hits DB each time parameter validation + Bloom filter + null short cache penetration rate ≈0
5 Cache breakdown hot key expiry instant concurrent fallback single key mutex + double-check / logical expiry + single-flight fallback concurrency =1
6 Cache avalanche many keys expire at once TTL random jitter + cluster HA + multi-level fallback + Sentinel rate limit circuit break no centralized expiry
7 Multi-level cache consistency L1 copies per node, write-time window update DB first→Outbox/binlog delete cache (guaranteed) + Pub/Sub broadcast clear L1 + delayed double-delete + version prevent old override inconsistency window <100ms, dirty read rate <0.001%
8 ES deep pagination OOM each shard returns from+size to coordinator search_after + unique tiebreaker + PIT + routing + disable track_total_hits P99<100ms
9 ES write amplification drags search high-frequency changes + real-time refresh segment merge pressure MQ async bulk micro-batch + larger refresh_interval + temporary lower replica + async translog data delay <3s
10 ES and DB inconsistency treating ES as source, sync dual-write CQRS: MySQL source of truth, binlog→MQ→ES idempotent overwrite + reconciliation compensation reconciliation diff <10/day
11 ES memory explode/slow aggregation text aggregation fielddata, big doc return keyword+doc_values, forbid text aggregation, only fetch ID detail back to Redis, pre-aggregation no fielddata OOM
12 Shard count planning too many fan-out explode, too few can't scale single shard 20–50GB per 3-month data, replica 1, ILM rolling shard size balance <20%
13 MQ backlog can't catch up production > consumption, queue count is parallelism ceiling first rate-limit degrade to C>P→expand threads/instances/queues→temporary Topic flood discharge→batch+backpressure 50M backlog caught up in 30min
14 Catch-up kills downstream consumption acceleration doubles DB/ES writes token bucket backpressure + downstream RT dynamic limit + 429 backoff + semaphore + batch DB write downstream zero alarm
15 Duplicate consumption retry, rebalance, batch ack replay eventId unique index + SETNX + version CAS + state machine + ES _id overwrite duplicate consumption zero business impact
16 Message disorder old status overwrites new orderId hash same partition + consumer hash bucket + version reject old + state machine only forward no illegal transition
17 Message loss DB success MQ fail / dual-write unreliable Outbox/transactional message + sync flush + manual ACK + DLQ manual replay event zero loss
18 Poison message blocks individual messages retry repeatedly block partition maxReconsumeTimes→DLQ + alarm isolation + replay compensation dead letter closed loop 24h
19 Fault cascade spread downstream slow drags whole chain cluster business isolation + gateway rate limit + circuit break degrade + active-active fallback page + main path only write DB and send MQ fault location <5min
20 Insufficient observability only know "slow" hit rate / ES P99 / MQ Lag + bulk reject + version conflict + DLQ + traceId + tiered alerts big-sale dashboard full coverage

7. Final Words

Looking back, this whole scheme is four sentences:

  1. Cache is not updated, it's deleted. Consistency relies on binlog/Outbox, availability on logical expiry, hit rate on layering.
  2. ES is not a database, it's a search index. Wide table + routing + filter + search_after; fast queries are designed.
  3. MQ is not a trash can, it's a flood-discharge channel. Catch-up ceiling is downstream capacity; idempotency is the license to speed up.
  4. High-concurrency systems fear inconsistency and uncontrollability more than slowness. Monitoring, rate limiting, degradation, idempotency, reconciliation matter more than just "adding cache".

Implementation order: first build the Outbox + idempotency + reconciliation foundation, then treat cache hit rate, then ES deep pagination and write async, finally rehearse the MQ catch-up plan. Let derived data controllably chase the source of truth around version numbers; with this main line firm, cache, ES, MQ can safely make eventual-consistency optimizations.

image.png

Finally an interaction question: what's your system's MQ backlog alarm threshold? Decided by guessing, or calculated by "catch-up time = Lag/(C-P)"? Discuss in comments; I'll pick a few to help check whether your consumption chain has the "96 machines watching" pit.

If you find this solid, hit like and wow, forward to colleagues in firefighting. Follow me to not get lost; next article plans to expand Redisson distributed lock source code and ES shard count calculation — comment 1 if interested.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

前端老董 1 likes

This good of an article gets so few views, you can see how the industry has withered by now.

Rain的Java大神之路

People are just busy, haha.