The user wants a design for a "large-scale batch inference system" with specific requirements:
- Orchestration: It needs to coordinate tasks.
- Checkpoint Restarts: It needs to handle failures gracefully by resuming from where it left off.
- Sharded Outputs: The output data needs to be partitioned (likely based on keys or ranges) for downstream processing.
- Retries: Failed tasks need to be attempted again.
This sounds like a system design interview question or a request for an architectural blueprint for a real-world data processing pipeline (e.g., using Spark, Ray, Flink, or a custom Kubernetes-based solution).
Key Components & Considerations:
- Input: Large dataset (e.g., millions of images or text documents) stored in a distributed file system (S3, HDFS).
- Inference Engine: The ML model (e.g., TensorFlow, PyTorch) loaded onto workers (CPU/GPU).
- Orchestrator: The "brain" managing the state of the jobs.
- Worker Pool: The compute resources performing the actual inference.
- State Management: Tracking progress (Checkpoints).
- Output Handling: Writing results to specific shards.
Architectural Pattern:
I should probably propose a "Controller-Worker" pattern or a "Master-Slave" pattern, but modern terminology prefers "Driver/Coordinator" and "Workers."
Addressing Specific Requirements:
-
Orchestration:
- How do we split work? Input sharding (e.g., splitting a file list).
- How do we distribute work? A task queue (e.g., SQS, Redis, or internal framework queue like Spark RDDs).
-
Checkpoint Restarts:
- Granularity: Per-record? Per-file? Per-batch? Per-batch is usually best for performance vs. overhead tradeoff.
- Mechanism: The worker processes a batch, writes a "marker" or "manifest" after successfully writing output, and reports back to the metadata store. If a worker dies, the orchestrator sees the incomplete task and re-issues it.
-
Sharded Outputs:
- This is tricky. If we just output files randomly, they aren't sharded by a key (e.g., user_id).
- Approach 1 (Map-Side Shuffle): Workers write to local temp files partitioned by key. Then a shuffle phase moves them to final destinations.
- Approach 2 (Direct Write): If the sharding logic is simple (e.g.,
hash(key) % N), workers can directly write to the specific output shard file (e.g., output_shard_0.parquet, output_shard_1.parquet).
- Atomicity: Writing to a temp location and renaming is crucial to avoid partial data.
-
Retries:
- Policy: Exponential backoff, max retry count.
- Scope: Retry the whole task (batch).
Proposed System Architecture (The "Design"):
- Technology Stack Choice: I should offer a generalized design but mention frameworks like Ray or Spark as implementation vehicles, or a custom Kubernetes + Redis approach for total control. Let's go with a high-level custom architecture using Kubernetes concepts, as it explains the mechanism better than just saying "use Spark." However, acknowledging that Spark/Ray handles much of this out-of-the-box is important context.
High-Level Flow:
- Job Submission: User sends config (model URI, input URI, output URI).
- Input Scan: List all input objects/files.
- Task Generation: Create "micro-batches" of work.
- Queueing: Push tasks to a Distributed Queue.
- Worker Execution:
- Pull task.
- Check Metadata Store (Checkpoint) -> Skip if done.
- Load Model.
- Inference.
- Sharding Logic: Hash the ID, write to specific buffer.
- Commit: Write output to S3 (multipart upload), update Metadata Store (Checkpoint).
- Failure Handling: If worker dies/crashes, lease expires -> Task becomes visible again -> Another worker picks it up.
Deep Dive into Specific Mechanics:
Structure of the Answer:
- Executive Summary: High-level goal and approach.
- Architecture Diagram (Text description): Components (Controller, Queue, Workers, Storage).
- Core Components Detail:
- Input Ingestion & Task Creation.
- The Worker Lifecycle (Model Loading, Inference).
- Checkpointing Strategy (The "Write-Ahead Log" concept).
- Output Sharding Strategy (The "Hash Partitioning" logic).
- Failure & Recovery: How retries work, handling "poison pills."
- Scalability & Performance: GPU utilization, batching.
- Tech Stack Recommendations: (Ray, Spark, or Custom K8s).
Refining the "Sharded Outputs" part:
This is often the hardest part for people to visualize.
- Scenario: Input is 1TB of logs.
- Task: Run NLP model to extract entities.
- Output Requirement: All logs for
user_id X must be in the same file.
- Solution:
- Worker reads a chunk of logs.
- Worker predicts.
- Worker loops through results.
target_shard = hash(user_id) % total_shards.
- Worker appends result to a local buffer for
target_shard.
- Worker flushes local buffers to cloud storage paths like
gs://bucket/output/shard_12/part-001.parquet.
- Issue: This creates many small files if not managed.
- Better Solution: A two-phase approach (Map -> Shuffle -> Reduce) is robust but slower. For "Batch Inference" usually Map-only with smart partitioning is preferred. I will describe the Map-side partitioning approach as it's common in large scale batch inference (like Spark mapPartitions).
Self-Correction during thought process:
-
Initial thought: Just use a database for checkpoints.
-
Correction: Too slow for millions of records. Use a high-throughput KV store (Redis/DynamoDB) or a file-based manifest system (Spark style). Let's stick to a high-throughput KV store (Redis/DynamoDB) for the custom design to illustrate the concept of "leases."
-
Refining Checkpoint Restart:
- We need to ensure we don't re-process completed work.
- The "Task ID" (e.g.,
file_001) is the key. If status(task_id) == SUCCESS, skip.
Drafting the Content:
I will structure this as a formal System Design document.
- Requirements: Functional & Non-Functional.
- System Architecture: Visualizing the flow.
- Key Features Implementation:
- Sharding: Hash-based partitioning.
- Checkpointing: Idempotent writes + Metadata tracking.
- Retries: Queue-based visibility timeouts.
- Scalability Considerations: GPU sharing, Batching.
Let's create the response. I will focus on a Kubernetes + Distributed Queue (SQS/Kafka) architecture because it forces us to design the mechanics explicitly, whereas saying "Just use Spark" hides the complexity the user wants to understand. I will add a note at the end about existing frameworks.
Checkpointing nuance:
We need to distinguish between "Checkpointing the Model" (not needed here, model is static) and "Checkpointing the Process" (resuming the job). The user asks for "Checkpoint restarts," implying process resumption.
Output Sharding nuance:
Sharding implies grouping.
Common trap: Every worker writing to the same file (locking issues).
Solution: Workers write to partitioned files, or workers write to temporary files which are merged later. I will propose Direct Partitioned Writes (writing to specific shards based on hash) as it's efficient for inference.
Let's go.
Designing a large-scale batch inference system requires a robust architecture that handles state management, fault tolerance, and data parallelism. Below is a comprehensive design for a system orchestrating checkpoint restarts, sharded outputs, and retries.
1. High-Level Architecture
We will design a Distributed Driver-Worker Pattern. This pattern separates the control plane (orchestration) from the data plane (inference).
Core Components
- Object Store (The Data Lake): Stores input data, model artifacts, and final outputs (e.g., S3, GCS, Azure Blob).
- State Store (The Brain): A low-latency, strongly consistent key-value store (e.g., Redis, DynamoDB, Etcd) used for tracking task progress, locks, and heartbeats.
- Job Manager (Driver): A lightweight process responsible for:
- Partitioning input data into micro-batches.
- Dispatching tasks to the queue.
- Monitoring system health.
- Task Queue: A high-throughput message queue (e.g., RabbitMQ, SQS, or Redis Streams) holding pending inference tasks.
- Inference Workers: Stateless compute nodes (Kubernetes Pods/EC2 instances) that pull tasks, load models, and perform inference.
2. Orchestration & Task Lifecycle
To handle large scales, we avoid "push" mechanisms where the driver forces work onto workers. Instead, we use a Pull-Based Consumer Model.
2.1 Input Partitioning (Sharding the Input)
The Job Manager does not process data; it scans the input manifest.
- The Manager lists all input objects (e.g., 100,000 image paths).
- It groups these into Inference Batches (e.g., batches of 100 images).
- It assigns a unique
Task_ID and a deterministic Output_Shard_ID to each batch.
2.2 Task State Machine
Every task follows a strict state flow stored in the State Store:
PENDING → RUNNING → COMPLETED / FAILED
3. Detailed Feature Implementation
Feature A: Checkpoint Restarts (Resumability)
If the job crashes or spot instances are reclaimed, the system must restart exactly where it stopped without re-computing finished work.
The Mechanism:
We utilize Idempotent Task Processing combined with a Check-bitmap.
- Pre-execution Check: When a Worker picks up a task from the Queue, it queries the State Store:
- Query:
GET task_status:{Task_ID}
- The Logic:
- If status is
COMPLETED: Drop the task (it was already done). This handles "at-least-once" queue delivery.
- If status is
NONE: Claim the task by setting status to RUNNING (with a TTL lease).
- The Restart:
- If the Job Manager restarts, it simply re-queues all task IDs.
- The Workers effectively "filter" out the completed ones by checking the State Store.
- Optimization: The Job Manager can query the State Store for the list of
COMPLETED IDs and only queue the delta (the missing tasks).
Feature B: Sharded Outputs
Writing millions of small files (one per inference) creates latency and cost issues (the "small files problem"). We aggregate results into Shards (e.g., Parquet or TFRecord files).
The Mechanism:
Each Inference Worker writes to a specific shard based on a hashing scheme or pre-assignment.
- Shard Assignment:
Task metadata contains Target_Shard_ID.
- Buffering: The Worker processes the batch. Instead of writing one result file, it appends the result to a local buffer for that shard.
- Commit Phase:
- Because multiple workers might write to the same logical shard, we usually partition shards physically (e.g.,
shard_01_part_0.parquet, shard_01_part_1.parquet).
- For strict aggregation, workers use a distributed commit log or upload partial shards to a "staging" folder.
- A lightweight Compaction Job (separate from inference) runs periodically to merge partial shards into final large files.
Feature C: Retries & Fault Tolerance
Hardware fails. Models OOM (Out of Memory). Network blips occur.
The Mechanism:
- Visibility Timeout (Lease):
- When a Worker pulls a task, it has a "Lease" (e.g., 10 minutes).
- If the Worker dies, the lease expires, and the Task Queue makes the message visible again for another worker to pick up.
- Retry Policy:
- We track a
retry_count in the State Store.
- Transient Failures (Network/IO): Automatic retry with exponential backoff.
- Inference Failures (Bad Data): If a specific input row causes a crash, the Worker catches the exception, logs the error to a "Dead Letter Queue" (DLQ) output, and marks the task as
COMPLETED_WITH_ERRORS. This prevents the pipeline from stalling forever on a "poison pill" image.
- Exhausted Retries: If
retry_count > max_retries, move to DLQ.
4. The Inference Worker Loop (Pseudocode)
This logic runs inside every Worker container:
def worker_loop():
model = load_model() # Load once
while True:
# 1. Get Task
task = queue.receive_message(visibility_timeout=600)
if not task: break
task_id = task.id
input_batch = task.data_refs
shard_id = task.shard_id
# 2. Checkpoint Check (Idempotency)
if state_store.get(task_id) == "COMPLETED":
queue.delete_message(task)
continue
try:
# 3. Claim Task
state_store.set(task_id, "RUNNING", ttl=600)
# 4. Process
inputs = object_store.read(input_batch)
results = model.predict(inputs)
# 5. Write Sharded Output
# Write to a specific partition file (e.g. shard_01_worker5.parquet)
output_path = f"s3://outputs/run_id/shard_{shard_id}_tmp_{worker_id}.parquet"
object_store.write(output_path, results)
# 6. Commit
state_store.set(task_id, "COMPLETED")
queue.delete_message(task)
except OOMError:
# Specific handling: Reduce batch size and retry?
state_store.set(task_id, "FAILED_OOM")
# Trigger alert
except Exception as e:
# Retry Logic
current_retries = state_store.increment_retry(task_id)
if current_retries > MAX_RETRIES:
state_store.set(task_id, "DEAD_LETTER")
else:
# Task becomes visible in queue again after timeout
log.error(f"Task failed, retrying: {e}")
5. Handling "Exactly-Once" Semantics
Achieving exactly-once processing in batch inference is difficult because inference is a side effect (writing to a file).
-
The Problem: A worker processes a task, writes the output to S3, but crashes before updating the State Store to COMPLETED. The queue makes the task visible again. Another worker picks it up. Now we have duplicate inference data.
-
The Solution (Output Deduplication):
- Approach 1 (Randomized Suffixes): Workers write to unique filenames (
result_worker_A.parquet). If a task is re-run, it writes to result_worker_B.parquet. The downstream compaction job deduplicates based on input ID columns.
- Approach 2 (Atomic Commit - Strict): The worker writes output, but before marking
COMPLETED, it checks if the output file already exists.
6. Technology Stack Recommendations
- Orchestration: Ray Data or Apache Spark.
- Why: They have built-in logic for lineage, retries, and sharding. If building from scratch (as designed above), use Python + Redis + RQ/Celery or Go + Redis.
- State Store: Redis (Cluster mode) for speed.
- Queue: AWS SQS (managed) or Kafka (high throughput).
- Compute: Kubernetes (K8s) with KEDA (Kubernetes Event-driven Autoscaling) to scale workers based on queue depth.
Summary of Data Flow
- Job Manager scans S3 Input, creates Tasks.
- Tasks pushed to Queue.
- Worker pulls Task.
- Worker checks State Store (Redis) -> If
COMPLETED, stop.
- Worker sets State to
RUNNING.
- Worker downloads batch -> Runs Model -> Uploads to Output Shard.
- Worker sets State to
COMPLETED.
- Compaction Job merges partial shards into final dataset.