We are designing a large-scale batch inference system that must handle:
- Checkpoint restarts: ability to resume from a known state in case of failures.
- Sharded outputs: distribute output data across multiple files/servers for scalability.
- Retries: automatic retry of failed batches with backoff.
We assume the system processes a large dataset in batches. The system should be fault-tolerant and scalable.
Components:
- Input: A large dataset, possibly stored in a distributed file system (like HDFS, S3) or a database.
- Batch Splitter: Splits the input into manageable batches (maybe by rows or by some key).
- Checkpoint Manager: Tracks which batches have been successfully processed and stores intermediate state.
- Inference Workers: These are the actual inference engines (could be GPU workers) that process a batch.
- Output Writer: Writes the results of each batch to sharded output storage.
- Orchestrator: Coordinates the above components, handles retries, and monitors progress.
Steps:
-
Initialize:
- Load the checkpoint (if exists) to know which batches are already done.
- Determine the set of batches to process (from the input data and checkpoint).
-
For each batch (in parallel if possible):
- If the batch is already processed (according to checkpoint) and output exists, skip.
- Otherwise, assign the batch to an available worker.
-
Worker process:
- Load the batch data (from input storage).
- Run inference model (which might be a large neural network, so we need GPU).
- Write the output for this batch to a temporary location (or directly to the final sharded output?).
-
Checkpoint update:
- After a batch is successfully processed and output written, update the checkpoint to mark the batch as done.
-
Retry logic:
- If a worker fails (timeout, error, etc.), the orchestrator should reassign the batch after a delay (with exponential backoff?).
- We might set a maximum number of retries per batch.
-
Sharded outputs:
- The output for each batch should be written to a shard. We can use a consistent sharding scheme (e.g., by batch index mod N, or by a key in the data).
- We might want to combine the shards at the end, or leave them sharded for downstream processing.
-
At the end, when all batches are done, we might:
- Merge the sharded outputs into a single file (optional, depending on use case).
- Write a final manifest or index.
Implementation considerations:
-
We need a way to distribute work and track state. This could be done with a central orchestrator (like a master node) or in a decentralized way (using a queue and workers that pull jobs).
For large scale, we might use a distributed task queue (e.g., Celery, Redis Queue, or a custom solution with a database).
-
Checkpoint storage: We need a durable storage for the checkpoint (like a database or a file in distributed storage). The checkpoint should record:
- List of completed batches (or a bitmap, or a set of batch IDs).
- Possibly the location of the output for each batch (or we can reconstruct from sharding scheme).
-
Output sharding: We can design the output sharding so that each batch writes to a specific shard file. We might have a fixed number of shards (say, 1000) and assign each batch to a shard by (batch_id % num_shards). Then we write the batch's results to that shard. However, note that multiple workers might write to the same shard concurrently. We need to handle that:
Option 1: Each shard is written by only one worker at a time. We can have a lock per shard, but that might be complex.
Option 2: Each worker writes to a temporary file for the shard and then we merge the temporary files for each shard at the end. But that would require an extra merge step and double the storage.
Option 3: Use a distributed file system that supports concurrent appends (like HDFS with append, but it's not recommended for many concurrent writers) or use a database (but that might be slow for large outputs).
Option 4: Have a writer service per shard that receives the data from workers via RPC and writes sequentially. This adds complexity but ensures sequential writes.
Alternatively, we can avoid concurrent writes by having each batch write to a unique temporary file (named by batch ID) and then have a separate step that combines the temporary files into the final shards. This is simpler and leverages the fact that we already have a checkpoint and we know which batches are done. Then, we can run a shard combiner that:
- For each shard, collects all the temporary files for batches assigned to that shard and concatenates them (or processes them in order) to produce the final shard.
However, note that the temporary files might be large and we might run out of storage if we keep both temporary and final. We can do:
Step 1: Each worker writes the batch output to a temporary location (with batch ID in the name).
Step 2: After the batch is successfully written, we update the checkpoint and then (in a separate process) move/rename the temporary file to the final shard? But then we have concurrent writes to the same shard from multiple batches? Actually, if we use the sharding by batch ID mod N, then multiple batches will write to the same shard. We cannot have multiple workers writing to the same file concurrently.
-
Orchestrator design:
We can have a master orchestrator that:
- Maintains a list of batches to process (from the input data and checkpoint).
- Distributes batches to workers (via a task queue, or by assigning directly if we have a fixed set of workers).
Alternatively, we can use a pull-based model:
-
Workers pull batches from a central queue (like a Redis list or a database table of pending batches). The queue is initialized with all batches that are not done (according to checkpoint).
-
When a worker picks a batch, it marks it as "in progress" in the checkpoint (or in the queue) so that other workers don't pick it.
-
After the worker finishes, it writes the output and updates the checkpoint to "done".
-
If the worker fails, the batch remains "in progress" and after a timeout, the orchestrator (or a separate monitor) will reset it to "pending" so it can be retried.
We need a way to track the state of each batch:
states: pending, in_progress, done, failed (and maybe retry count).
We can have a database table:
batch_id | status | retry_count | worker_id | last_updated
The orchestrator:
- At startup, loads the checkpoint (from the database) and then enqueues all batches that are not done (or failed with retry_count < max_retries).
- Then, workers can pull from the queue (by selecting a batch with status='pending' and updating it to 'in_progress' and setting worker_id and timestamp). We need to do this atomically.
- Workers process the batch and then update the status to 'done' (and clear worker_id) and also record the output file path.
- If a worker fails, the batch remains in 'in_progress' and the orchestrator (or a sweeper) will periodically check for batches that have been in 'in_progress' for too long and reset them to 'pending' (and increment retry_count). If retry_count exceeds max, then mark as 'failed' and alert.
This is a classic work queue pattern.
-
Scalability:
-
The database for the batch state might become a bottleneck if we have millions of batches. We can partition by batch ID or use a distributed database.
-
The queue can be implemented with a distributed queue (like RabbitMQ, Kafka, or a sharded Redis).
-
The output storage must be able to handle many writes (to different shard directories) and then the final concatenation.
-
Fault tolerance:
- The checkpoint database should be replicated.
- The input and output storage should be durable (like HDFS, S3).
- Workers should be stateless and can be killed and restarted.
11. Implementation plan:
Step 1: Preprocessing
- Split the input data into batches (by row count, or by some key). We need to generate a list of batch IDs and the corresponding input data locations (e.g., file paths and offsets, or database query ranges).
We can store this list in the checkpoint database as well, or we can have a separate input manifest.
Step 2: Initialize the batch state table (if not exists) by:
- If checkpoint exists, load the state from there.
- Otherwise, create entries for all batches with status='pending'.
Step 3: Start the orchestrator and workers.
Step 4: Workers:
while True:
- Pull a batch (atomically mark as in_progress).
- If no batch, sleep and retry.
- Load the batch data (from the input location specified for that batch).
- Run the model inference.
- Write the output to: output_dir/shard_<shard_id>/batch_<batch_id>.out
- Update batch status to 'done' and record output file path.
If any error, throw an exception and let the batch be retried (by not updating to done).
Step 5: Sweeper (could be part of orchestrator or separate):
Periodically (every few minutes):
- Find batches with status='in_progress' and last_updated older than a threshold (e.g., 1 hour).
- Reset them to 'pending' and increment retry_count.
- If retry_count >= max_retries, set status='failed' and alert.
Step 6: After all batches are done (or a certain percentage, or after a timeout), run the combiner:
For each shard_id in range(num_shards):
- List all files in output_dir/shard_<shard_id> that match batch_*.out.
- Sort by batch_id (extract from filename).
- Concatenate in order to output_dir/shard_<shard_id>.final
- Delete the individual batch files.
Alternatively, we can run the combiner per shard as soon as the first batch for that shard is done? But then we might have to append later? We can have the combiner run incrementally, but then we need to manage the state of which batches have been combined. Since we already have the checkpoint, we know which batches are done. We could have the combiner for a shard process all done batches for that shard and then mark them as combined in a separate table? That adds complexity.
Given the simplicity, I would do the concatenation at the end.
12. Monitoring:
- We need to monitor the progress (number of batches done, failed, pending).
- We can have a dashboard that reads from the batch state table.
13. Example technology stack:
- Orchestrator/workers: Python with Celery (if using Redis as broker and result backend) or custom with a database.
- Checkpoint storage: PostgreSQL or MySQL (for relational) or Redis (for fast access, but need persistence) or a distributed key-value store.
- Input data: HDFS, S3, or a database.
- Output: HDFS, S3, or a distributed file system.
14. Code structure (pseudo-code):
// Preprocessing script
batches = split_input(input_data)
for batch in batches:
insert into batch_table (batch_id, status, retry_count, input_location, shard_id) values (batch.id, 'pending', 0, batch.location, batch.id % num_shards)
// Worker
while True:
batch = db.execute("SELECT * FROM batch_table WHERE status='pending' ORDER BY batch_id LIMIT 1 FOR UPDATE SKIP LOCKED").fetchone()
if not batch:
sleep(10)
continue
db.execute("UPDATE batch_table SET status='in_progress', worker_id=:worker_id, last_updated=now() WHERE batch_id=:batch_id", worker_id=my_id, batch_id=batch.batch_id)
try:
data = load_data(batch.input_location)
results = model.infer(data)
output_path = f"output_dir/shard_{batch.shard_id}/batch_{batch.batch_id}.out"
write_results(results, output_path)
db.execute("UPDATE batch_table SET status='done', output_path=:output_path, worker_id=NULL, last_updated=now() WHERE batch_id=:batch_id", output_path=output_path, batch_id=batch.batch_id)
except Exception as e:
log_error(e)
// We leave the batch as 'in_progress' and let the sweeper reset it after timeout.
// Sweeper (runs in orchestrator or separate)
while True:
sleep(300) // every 5 minutes
now = time.time()
threshold = now - 3600 // 1 hour
batches = db.execute("SELECT * FROM batch_table WHERE status='in_progress' AND last_updated < :threshold", threshold=threshold)
for batch in batches:
new_retry = batch.retry_count + 1
if new_retry >= max_retries:
db.execute("UPDATE batch_table SET status='failed' WHERE batch_id=:batch_id", batch_id=batch.batch_id)
alert(batch.batch_id)
else:
db.execute("UPDATE batch_table SET status='pending', retry_count=:retry, worker_id=NULL, last_updated=now() WHERE batch_id=:batch_id", retry=new_retry, batch_id=batch.batch_id)
// Combiner (run after all batches are done or periodically)
for shard_id in range(num_shards):
files = list_files(f"output_dir/shard_{shard_id}/batch_*.out")
// sort by batch_id (extract from filename)
sorted_files = sort(files, key=lambda x: extract_batch_id(x))
with open(f"output_dir/shard_{shard_id}.final", "wb") as outfile:
for f in sorted_files:
with open(f, "rb") as infile:
shutil.copyfileobj(infile, outile)
// delete the batch files
for f in sorted_files:
os.remove(f)
15. Improvements:
- The combiner can be parallelized by shard (each shard independently).
- We can compress the output files if needed.
- We can have a limit on the number of concurrent workers per shard? Not necessary because each batch writes to a separate file.
16. Potential issues:
- The batch state table might become large. We can archive done batches after a while.
- The output directory might have millions of small files (if we have many batches and many shards). This can be a problem for some file systems (like HDFS, which has a limit on the number of files in a directory). We can mitigate by:
* Using a two-level directory structure: output_dir/shard_<shard_id>/<batch_id%1000>/batch_<batch_id>.out
* Or, we can have the combiner run more frequently (e.g., after every 100 batches for a shard) and then delete the temporary files, so we don't accumulate too many.
- The combiner might be I/O intensive. We can run it on a machine with high network bandwidth and disk I/O.
17. Conclusion:
This design provides a robust, scalable batch inference system with checkpointing, retries, and sharded outputs. The use of temporary files per batch and a final concatenation step avoids concurrent write issues and simplifies the workers.
However, note that the temporary files might take up significant space until the combiner runs. We can run the combiner incrementally (per shard) as soon as, say, 100 batches are done for that shard. But then we need to track which batches have been combined. We can do:
- Add a 'combined' flag in the batch table? Or have a separate table that records which batches have been combined.
Alternatively, we can have the combiner for a shard run and then update the batch table to mark those batches as 'combined'. But then we have to be careful about the order.
Given the complexity, I would stick with the simple approach of running the combiner at the end, unless storage is a major concern.
If storage is a concern, we can:
- Have the worker write to a temporary directory (maybe on local disk) and then move to the shard directory? But then we are moving large files, which is I/O intensive.
- Or, we can have the worker write to the shard directory but with a temporary name and then rename to the final batch name? That doesn't help with the number of files.
So, the number of files in the shard directory is the number of batches for that shard. If we have 1 million batches and 1000 shards, then each shard has 1000 files on average. That's acceptable. If we have 1 billion batches and 1000 shards, then each shard has 1 million files. That might be too many for a single directory. So we need a two-level directory:
output_dir/shard_<shard_id>/<batch_id % 1000>/batch_<batch_id>.out
Then, the combiner would need to traverse the subdirectories.
We can adjust the directory structure based on the expected number of batches.
18. Final note:
The system can be implemented in any language, but Python is a good choice for the orchestrator and workers because of the rich ecosystem for machine learning (TensorFlow, PyTorch). However, for performance-critical parts, we might use C++ or Go.
We assume the inference model is loaded once per worker (and kept in memory). So the worker should be long-lived.
We also assume that the batch size is fixed and the model can handle it.
If the model is too large to fit in one GPU, we might need model parallelism, which complicates the worker. But that's beyond the scope of this design.
19. Summary:
- Split input into batches and record in a database.
- Workers pull batches, process, and write to sharded temporary files (one file per batch, in a directory per shard).
- Checkpoint database tracks the status of each batch.
- Sweeper resets stuck batches with retry limit.
- Combiner concatenates the temporary files for each shard into a final shard file and deletes the temporary files.
This design is simple, robust, and scalable.
20. Extensions:
- We can add a priority system for batches (if some are more urgent).
- We can have different models for different batches (by storing the model id in the batch record and having workers load the appropriate model).
- We can have the output format be something like Parquet or Avro for efficient storage and querying.
But these are beyond the basic requirements.</think>
I'll design a comprehensive large-scale batch inference system with checkpoint/restart, sharded outputs, and intelligent retries. This system handles billions of predictions with fault tolerance.
System Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ ORCHESTRATION LAYER │
├─────────────┬─────────────┬──────────────┬─────────────────┤
│ Scheduler │ Monitor │ Retry │ Checkpoint │
│ │ │ Manager │ Manager │
└──────┬──────┴──────┬──────┴──────┬───────┴──────┬──────────┘
│ │ │ │
┌──────▼─────────────▼─────────────▼──────────────▼──────────┐
│ WORKER POOL (Auto-scaling) │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ Worker 1 │ Worker 2 │ Worker N │ GPU/CPU Pool │
│ (GPU) │ (GPU) │ (CPU) │ │
└──────┬──────┴──────┬──────┴──────┬──────┴──────┬──────────┘
│ │ │ │
┌──────▼─────────────▼─────────────▼──────────────▼──────────┐
│ SHARDED OUTPUT STORAGE │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Shard 0 │ │Shard 1 │ ... │Shard N-1│ │
│ │_part_0 │ │_part_0 │ │_part_0 │ │
│ │_part_1 │ │_part_1 │ │_part_1 │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└───────────────────────────────────────────────────────────┘
Core Components
1. Input Processor & Batcher
class InputBatcher:
def __init__(self, input_source, batch_size=1000,
shard_key_fn=None, max_shards=1000):
self.input_source = input_source # Could be DB, file, stream
self.batch_size = batch_size
self.shard_key_fn = shard_key_fn or (lambda x: hash(x) % max_shards)
self.max_shards = max_shards
def generate_batches(self):
"""Stream batches with deterministic shard assignment"""
for shard_id in range(self.max_shards):
yield from self._batches_for_shard(shard_id)
def _batches_for_shard(self, shard_id):
"""Get all batches for a specific shard (supports restart)"""
# Use checkpoint to resume from last processed record
last_position = checkpoint.get_shard_position(shard_id)
# Stream only records for this shard_key
# ...
2. Checkpoint Manager
class CheckpointManager:
def __init__(self, storage_backend, checkpoint_interval=1000):
self.backend = storage_backend # S3, GCS, HDFS, DB
self.checkpoint_interval = checkpoint_interval
self.state_lock = distributed_lock()
def save_checkpoint(self, batch_id, shard_id, position,
metadata=None, force=False):
"""Atomic checkpoint save with versioning"""
checkpoint_data = {
'batch_id': batch_id,
'shard_id': shard_id,
'position': position,
'timestamp': time.time(),
'metadata': metadata or {},
'version': self._next_version()
}
with self.state_lock:
# Write to temp then atomic rename
temp_path = f"checkpoints/tmp/{uuid.uuid4()}"
self.backend.write_json(temp_path, checkpoint_data)
final_path = f"checkpoints/shard_{shard_id}/latest.json"
self.backend.rename(temp_path, final_path)
def get_shard_state(self, shard_id):
"""Get last successful position for shard"""
try:
checkpoint = self.backend.read_json(
f"checkpoints/shard_{shard_id}/latest.json"
)
return checkpoint['position']
except FileNotFoundError:
return 0 # Start from beginning
3. Distributed Task Queue with Priority
class PriorityTaskQueue:
def __init__(self, redis_conn, queue_prefix="inference:"):
self.redis = redis_conn
self.prefix = queue_prefix
def enqueue_batches(self, batches, priority=0):
"""Add batches to queue with shard-based prioritization"""
pipe = self.redis.pipeline()
for batch in batches:
# Key: queue:shard_id:priority
queue_key = f"{self.prefix}queue:{batch.shard_id}:{priority}"
pipe.zadd(queue_key, {batch.id: time.time()})
# Also track by batch ID for deduplication
pipe.setex(f"{self.prefix}batch:{batch.id}", 86400, "queued")
pipe.execute()
def dequeue_batch(self, worker_id, timeout=30):
"""Atomic dequeue with lease mechanism"""
# Try higher priority queues first
for priority in [0, 1, 2]: # 0=high, 2=low
queue_key = f"{self.prefix}queue:*:{priority}"
batch_id = self.redis.zpopmin(queue_key, 1)
if batch_id:
# Set lease to prevent timeout losses
lease_key = f"{self.prefix}lease:{batch_id}"
self.redis.setex(
lease_key,
timeout,
f"{worker_id}:{time.time()}"
)
return self._get_batch_data(batch_id)
return None
4. Worker with Circuit Breaker & Retry Logic
class InferenceWorker:
def __init__(self, worker_id, model, max_retries=3,
retry_backoff='exponential'):
self.worker_id = worker_id
self.model = model
self.max_retries = max_retries
self.retry_backoff = retry_backoff
self.circuit_breaker = CircuitBreaker(
failure_threshold=5,
recovery_timeout=60
)
def process_batch(self, batch):
"""Process batch with retry semantics"""
retry_count = batch.get('retry_count', 0)
shard_id = batch['shard_id']
while retry_count <= self.max_retries:
try:
with self.circuit_breaker:
# Load checkpoint position if exists
start_idx = checkpoint.get_shard_position(shard_id)
# Process batch
results = self.model.predict(batch['data'])
# Write to sharded output
self._write_sharded_output(
results,
shard_id,
batch['batch_id']
)
# Update checkpoint
checkpoint.save_checkpoint(
batch_id=batch['batch_id'],
shard_id=shard_id,
position=start_idx + len(batch['data'])
)
return True
except (ModelTimeoutError, TemporaryGPUError) as e:
retry_count += 1
wait_time = self._calculate_backoff(retry_count)
logger.warning(f"Retry {retry_count} for batch "
f"{batch['batch_id']} in {wait_time}s")
time.sleep(wait_time)
continue
except PermanentError as e:
logger.error(f"Permanent failure for batch "
f"{batch['batch_id']}: {e}")
self._record_failure(batch, str(e))
return False
# Max retries exceeded
self._record_failure(batch, "max_retries_exceeded")
return False
5. Sharded Output Writer
class ShardedOutputWriter:
def __init__(self, output_base, num_shards=1000,
compression='snappy'):
self.output_base = output_base
self.num_shards = num_shards
self.compression = compression
self._shard_writers = {} # Cache open file handles
def get_shard_path(self, shard_id, batch_id):
"""Deterministic path: output/shard_{shard_id}/part_{batch_id}.parquet"""
return f"{self.output_base}/shard_{shard_id}/part_{batch_id:08d}.parquet"
def write_batch(self, results, shard_id, batch_id):
"""Write batch to appropriate shard"""
path = self.get_shard_path(shard_id, batch_id)
# Ensure directory exists
os.makedirs(os.path.dirname(path), exist_ok=True)
# Write with compression
if self.compression:
results.write_parquet(path, compression=self.compression)
else:
results.write_parquet(path)
# Optional: Sync to ensure durability
if self.sync_on_write:
os.fsync(os.open(path, os.O_RDONLY))
6. Retry Manager with Exponential Backoff
class RetryManager:
def __init__(self, redis_conn, max_retries=3,
backoff_strategy='exponential'):
self.redis = redis_conn
self.max_retries = max_retries
self.backoff_strategy = backoff_strategy
def schedule_retry(self, batch_id, shard_id, failure_reason,
attempt_count):
"""Schedule retry with jitter"""
if attempt_count >= self.max_retries:
self._move_to_dead_letter_queue(batch_id, failure_reason)
return
# Calculate backoff with jitter
base_delay = min(300, 2 ** attempt_count) # Cap at 5 minutes
jitter = random.uniform(0, 0.1 * base_delay)
delay = base_delay + jitter
# Schedule retry in priority queue
retry_queue = f"retry:shard_{shard_id}:{attempt_count}"
self.redis.zadd(
retry_queue,
{batch_id: time.time() + delay}
)
# Update batch status
self.redis.hset(
f"batch:{batch_id}",
mapping={
'status': 'retrying',
'retry_count': attempt_count + 1,
'last_error': failure_reason,
'next_retry_at': time.time() + delay
}
)
Workflow Example
def orchestrator_main():
"""Main orchestration loop"""
checkpoint_mgr = CheckpointManager(S3Storage())
task_queue = PriorityTaskQueue(Redis())
retry_mgr = RetryManager(Redis())
while True:
# 1. Load all shard states
shard_states = {}
for shard_id in range(NUM_SHARDS):
pos = checkpoint_mgr.get_shard_state(shard_id)
shard_states[shard_id] = pos
# 2. Generate new batches from input source
for shard_id, position in shard_states.items():
new_batches = generate_batches_from_position(
shard_id, position
)
task_queue.enqueue_batches(new_batches)
# 3. Process retry queue
for shard_id in range(NUM_SHARDS):
retry_batches = retry_mgr.get_ready_retries(shard_id)
task_queue.enqueue_batches(retry_batches, priority=1) # Higher priority
# 4. Wait for checkpoint sync
time.sleep(CHECKPOINT_SYNC_INTERVAL)
Fault Tolerance Features
1. Exactly-Once Semantics
- Idempotent processing: Each batch has unique ID
- Checkpoint before commit: Write checkpoint only after output confirmed
- Atomic operations: Use
compare-and-set for checkpoint updates
2. Failure Scenarios Handled
| Failure Type | Handling Mechanism | Recovery Time |
|---|
| Worker crash | Task lease expiration → requeue | < 2x lease time |
| Network partition | Circuit breaker → retry later | Exponential backoff |
| Output storage full | Backpressure → pause scheduling | Monitor alert |
| Model corruption | Health checks → drain worker | Immediate |
3. Data Consistency Guarantees
1. At-most-once processing:
- Each batch ID processed once
- Checkpoint updates are idempotent
2. Shard completeness:
- Each shard has contiguous batch IDs
- Missing batches detected via manifest
3. Output validation:
- Checksum per batch file
- Manifest with batch_id → shard mapping
Deployment Configuration
# config.yaml
system:
num_shards: 1000
batch_size: 1000
checkpoint_interval: 1000 # batches
max_retries: 3
resources:
worker:
min_instances: 10
max_instances: 1000
auto_scale_metrics:
- queue_depth > 1000 → scale up
- cpu_util < 30% for 5m → scale down
storage:
checkpoint_backend: "s3://bucket/checkpoints/"
output_base: "s3://bucket/inference-results/"
temp_directory: "/tmp/inference-worker/"
monitoring:
metrics_port: 9090
log_level: "INFO"
alerts:
- dead_letter_queue_size > 100 → pagerduty
- checkpoint_stalage > 1h → slack
Operations & Monitoring
Key Metrics to Track
# Queue metrics
inference_queue_depth{shard_id="0",priority="0"} 142
inference_batches_retried_total 125
# Worker metrics
inference_worker_active 47
inference_worker_circuit_breaker_state 0 # 0=closed, 1=open
# Checkpoint metrics
inference_checkpoint_age_seconds{shard_id="0"} 45.2
inference_checkpoint_missing_batches{shard_id="0"} 0
# Output metrics
inference_output_files_total 15432
inference_output_bytes_per_shard{shard_id="0"} 1.2e10
Recovery Procedures
- Worker failure: Automatically requeues after lease expiry
- Master failure: Stateless orchestrator; any instance can take over
- Storage failure: Cross-region replication for checkpoints
- Data corruption: Re-process from last valid checkpoint
Scaling Considerations
Horizontal Scaling
- Stateless workers: Any worker can process any batch
- Shard-based partition: Each shard can be processed independently
- Autoscaling triggers:
- Queue depth per shard
- Worker CPU/GPU utilization
- Checkpoint staleness
Vertical Scaling
- GPU workers: For heavy models
- High-memory workers: For large batches
- High-throughput workers: For I/O-bound models
Example Scenario
Input: 1B records, batch_size=1000 → 1M batches
Shards: 1000 (each ~1000 batches)
Normal operation:
Worker 1: Processes shard_0 batches 0-999 → writes 1000 files
Worker 2: Processes shard_1 batches 0-999 → writes 1000 files
...
Failure scenario:
Worker 45 fails while processing shard_45 batch_567
→ Circuit breaker opens
→ Task lease expires after 2 minutes
→ Orchestrator requeues batch_567 to retry queue
→ Worker 203 picks up batch_567 from retry queue (priority=1)
→ Success on 2nd attempt
Checkpoint restore:
System restart:
1. Read checkpoint for each shard
2. For shard_45: last_successful_batch=566
3. Generate batches starting from 567
4. Resume processing without duplication
Benefits of This Design
- Fault-tolerant: Exactly-once processing with leases and checkpoints
- Scalable: Shard-based parallelism, auto-scaling workers
- Observable: Comprehensive metrics and alerts
- Recoverable: Can restart from any failure point
- Resource-efficient: Backpressure prevents overload
- Cloud-native: Works with S3/GCS, containerized workers
This system can handle billions of inferences with minimal human intervention, automatically recovering from worker failures, network issues, and transient errors while maintaining data integrity.