Consume billions of compressed message files/hour, uncompress, and deliver to downstream (tight latency, limited hardware)

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2022-06-07

Problem Statement

Design a system that reliably ingests very high volume compressed files (many messages per file), streams the contained messages after decompression to downstream consumers (queues / processors / storage) with bounded latency, operating under constrained CPU/IO resources. The system must be fault tolerant, backpressure-aware, and cost-efficient.


2. Goals & assumptions


Goals


•Ingest and process billions of files/hour (scale horizontally).
•Uncompress and parse messages with low end-to-end latency.
•Provide backpressure, retries, checkpoints, monitoring.
•Operate efficiently on limited hardware (maximize work per core / GB).


Key assumptions


•Files are uploaded to durable object storage (S3/MinIO) or pushed to the ingest API.
•Files contain many messages (JSON/Avro/Protobuf). Average compressed size S_c and uncompressed S_u are known.
•Common compression codecs: zstd, gzip, lz4, snappy.
•Downstream accepts messages via a durable message bus (Kafka/Pulsar) or HTTP sinks.
•Delivery semantics: at-least-once by default; exactly-once optional with heavier cost.


3. Requirements


Functional


•Accept file metadata (path, codec, size) and schedule processing.
•Fetch and stream-decompress file bytes.
•Parse/validate messages and enrich with metadata (fileId, offset).
•Batch and deliver messages to downstream queue or API.
•Checkpoint progress per file; support retries & DLQ.


Non-functional


•High throughput (files/sec and messages/sec).
•Low median/95th percentile latency per message.
•Fault tolerance, backpressure and graceful degradation.
•Efficient resource usage (CPU, memory, network, local disk).
•Observability and dynamic throttling.


4. High-level architecture (components)

1 2Uploader/Producer -> Object Storage (S3) + Metadata Catalog 3 | 4 v 5 Scheduler / Coordinator 6 | 7 Assignment / Shard Map 8 | 9 Worker Pool (many nodes) 10 - Fetcher (range/stream reads) 11 - Decompressor (streaming / block-parallel) 12 - Parser (streaming) 13 - Batcher 14 - Dispatcher (to Message Bus / API) 15 | 16 v 17 Message Bus (Kafka/Pulsar) / Downstream APIs 18 | 19 Consumers


Supporting subsystems:


•Metadata Catalog (DB) for file state and checkpoints.
•Message Bus for decoupling and backpressure (preferred).
•Small KV store (Redis/RocksDB) for dedup/checkpoints.
•Monitoring & Alerting (Prometheus/Grafana, tracing).
•Control plane for throttling and reassignments.


5. Component responsibilities


Uploader: puts compressed files to storage and registers metadata (fileId, codec, size, priority).


Metadata Catalog: stores file state (PENDING, IN_PROGRESS, DONE, FAILED), worker assignment, progress offsets, retry counts.


Scheduler / Coordinator: assigns files to workers, enforces global concurrency limits, priorities, and throttles based on system health.


Worker (pipeline stages):


•Fetcher: streaming read of compressed bytes (range reads) into small chunks; emits to decompress queue.
•Decompressor: streaming decompression (zstd/gzip streaming APIs). For splittable formats, decompress blocks in parallel; otherwise use inter-file parallelism.
•Parser: streaming parse messages (SAX/streaming parser) and validate/enrich records.
•Batcher: accumulate records into byte/record batches (size or count threshold).
•Dispatcher: send batches to message bus (producer) or direct downstream; commits checkpoint after successful send.


Message Bus: durable buffer, partitioning for parallel consumption; enables smoothing and replay.


Downstream Consumers: idempotent where possible; read from bus, persist/compute.


Control & Monitoring: track lag, errors, queue sizes; signal scheduler to throttle or increase capacity.


6. Dataflow & sequencing (detailed)


1.Ingest: Client uploads to storage; registry entry created (fileId, codec, size).
2.Schedule: Coordinator picks file (PENDING) and assigns to worker.
3.Fetch: Worker streams compressed bytes (small chunks) — no full-file reads into memory.
4.Decompress: Streaming decompression emits byte stream to parser; if possible decompress different blocks in parallel.
5.Parse: Parser extracts messages, validates schema, attaches metadata.
6.Batch & Dispatch: Batches are formed and published to message bus or downstream API.
7.Checkpoint & Commit: After successful dispatch, worker updates Catalog offsets/checkpoints.
8.Finish: On EOF and successful commit, mark file DONE; emit metrics.


If failure occurs: worker retries from last checkpoint; after N attempts, file moved to DLQ/quarantine.


7. Worker design (pipeline + backpressure)


•Bounded stages: each stage connected via bounded queues (e.g., ring buffers). Sizes tuned to available memory.
•Stage parallelism: tune number of threads per stage (decompressors often CPU-bound, fetchers IO-bound, dispatchers network-bound).
•Backpressure: when dispatcher or message bus is slow, bounded queues fill and upstream naturally slows; scheduler can also stop assigning new files to that worker.
•Buffer reuse: use pooled byte buffers to reduce GC / allocation overhead.


8. Handling limited hardware: efficiency techniques


•Inter-file parallelism rather than heavy intra-file threads for non-splittable formats.
•Streaming processing — never fully buffer entire files. Use small chunk size (e.g., 64–512KB).
•Batching messages to amortize per-request overhead to downstream.
•Codec selection: if you control producers, prefer LZ4/snappy for speed; zstd for better compression/CPU trade-off.
•Zero-copy and buffer pools: reduce memory copies.
•Local caching of hot objects on SSD to avoid repeated network reads.
•Adaptive concurrency: workers reduce concurrency when CPU or memory pressure detected.
•Use efficient/native libraries (native zstd, rapidjson/Jackson streaming, Protobuf readers).


9. Delivery guarantees & deduplication


•Default: at-least-once delivery. Simpler, higher throughput.
•Exactly-once (optional): require transactional pipeline (Kafka transactional producers + atomic checkpoint commit) and/or global dedup store (idempotency keys in TTL store). High cost on throughput and latency.
•Dedup strategy: per-message unique ID included (fileId + offset + seq). Consumers can de-dup using local RocksDB or Redis with TTL.


10. Checkpointing & resume


•Workers persist per-file offsets (byte offset or message offset) into Catalog or local RocksDB checkpoint.
•On restart or reassignment, worker resumes from last committed offset to avoid reprocessing whole file.


11. Failure modes & behavior


•Worker crash: Coordinator detects missing heartbeat, reassigns file; new worker resumes from last checkpoint.
•Poisoned file/message: after repeated parse errors, move file to quarantine for offline inspection.
•Downstream slow / bus lag: backpressure triggers queue growth → scheduler reduces intake and slows assignment (protects memory).
•Network/storage outage: reties with exponential backoff; escalate if persistent.


12. Observability & SLOs


Monitor:


•files/sec, messages/sec, bytes/sec ingested
•per-file latency (arrival → last message dispatched)
•queue lengths at each stage
•CPU/memory/disk/network per worker
•message bus latency and lag
•error rates and DLQ rate


SLO examples:


•median per-message latency < X ms
•99.9% files processed within Y minutes
•retry rate < Z%


13. API surface & control plane


•POST /files — register file metadata (or callback from uploader)
•GET /files/{fileId}/status
•POST /admin/pause / POST /admin/resume
•POST /files/{fileId}/reprocess
•GET /metrics (Prometheus)
•GET /health


14. Capacity planning (formulas)


Given:


•F = files/hour
•S_c = avg compressed size (MB)
•S_u = avg uncompressed size (MB)
•D_core = decompression throughput per CPU core (MB/s)
•P_core = parsing throughput per core (MB/s or messages/s)


Compute compressed bytes/sec = F * S_c / 3600.


Decompression cores ≈ (F * S_c / 3600) / D_core (plus margin).


Parsing cores ≈ (F * S_u / 3600) / P_core.


Network read bandwidth ≈ compressed bytes/sec.


Downstream writing bandwidth ≈ messages/sec * avg message size.


Always add safety margin (20–50%) and account for coordinator, OS, and other overheads.


Important: plug real numbers — if the resulting required cores/bandwidth exceed available hardware, you must shard workload across more machines or relax SLAs.

15. Storage & bus choices


•Object Store: S3 or S3-compatible (durable storage).
•Message Bus: Kafka or Pulsar for durability, partitioning and replay (recommended).
•Metadata DB: Postgres/DynamoDB for file state and scheduling.
•Checkpoint & de-dup: RocksDB (local) or Redis for quick lookup.
•Local Cache: SSD for hot file caching / temporary decompressed blocks.


16. Security & governance


•Enforce access control on upload and processing APIs.
•Sanitize and validate file contents before parsing.
•Encrypt data in transit (TLS) and at rest (Bucket encryption).
•Audit logs for file registrations, reprocesses, and admin actions.


17. Trade-offs & final recommendations


•Batching vs latency: larger batches increase throughput but increase per-message latency. Tune per SLA.
•At-least-once (recommended) for performance; exactly-once only if business requires it.
•Message bus decouples and eases backpressure; use it unless downstream requires direct push with ultra-low latency.
•Codec choice affects CPU vs network usage — coordinate with producers to pick best trade-off for limited hardware.
•Profiling first: build a single-worker streaming prototype, measure D_core and P_core on representative data — then size cluster and tune.


18. Implementation checklist / roadmap


1.Prototype single-worker streaming pipeline; measure CPU/IO for target file distribution.
2.Implement bounded-stage worker with pooled buffers and streaming parser.
3.Add metadata catalog and checkpointing.
4.Add scheduler and worker pool; implement assignment & heartbeat.
5.Integrate message bus and downstream connectors.
6.Implement retries, DLQ, and admin controls.
7.Add monitoring, autoscaling rules and throttling.
8.Optimize (codec, batching, buffer sizes, SSD cache).


Solution

Comments