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.
•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)
12Uploader/Producer->ObjectStorage(S3)+MetadataCatalog3|4 v
5Scheduler/Coordinator6|7Assignment/ShardMap8|9WorkerPool(many nodes)10-Fetcher(range/stream reads)11-Decompressor(streaming / block-parallel)12-Parser(streaming)13-Batcher14-Dispatcher(toMessageBus/ API)15|16 v
17MessageBus(Kafka/Pulsar)/DownstreamAPIs18|19Consumers
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.
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.
•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)
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.