We are designing a batch scoring pipeline with the following requirements:
- Idempotent job orchestration: We need to ensure that the pipeline can be safely retried without duplicating work.
- S3 manifests: We'll use S3 to store data and manifests that list the files to be processed.
- Checkpointing: We need to save the state of the pipeline so that we can resume from where we left off in case of failures.
We'll design a pipeline that:
- Reads a manifest file (or list of manifest files) from S3 that lists the input files (e.g., in JSON or CSV format).
- Processes each file (scoring) and writes the output to S3.
- Keeps track of which files have been processed (checkpointing) to avoid reprocessing on retries.
Approach:
-
Manifest Files: The manifest will be a file (or set of files) in S3 that lists the S3 URIs of the input files to be processed. Each line in the manifest is an S3 URI.
-
Checkpointing: We will maintain a checkpoint file in S3 (or a database) that records the list of input files that have been successfully processed. Alternatively, we can have a manifest of processed files and a manifest of unprocessed files. However, for idempotency, we can design the pipeline to only process files that are not in the checkpoint.
-
Idempotency: The pipeline should be designed such that running the same job again (with the same manifest) does not reprocess the already processed files. We achieve this by:
- Before processing a file, check if it's in the checkpoint (i.e., already processed).
- After successfully processing a file, add it to the checkpoint.
-
Orchestration: We can use an orchestration tool like Apache Airflow, AWS Step Functions, or a simple script with state management. For simplicity, we'll design a script that can be run as a batch job (e.g., on an EMR cluster, EC2, or as a Lambda function if the manifest is small).
-
Scalability: If the number of files is large, we might want to parallelize the processing. However, for checkpointing and idempotency in a distributed setting, we need to be cautious about concurrent updates to the checkpoint. We can use a distributed lock or design the checkpoint to be append-only and then have each worker filter out already processed files.
Given the complexity of distributed checkpointing, let's assume we are running in a single node (or a single job) for now. If we need distributed processing, we can split the manifest and run multiple jobs, but then we need a shared checkpoint (like DynamoDB) and careful coordination.
Design for single-node (or single-job) processing:
Steps:
-
Download the manifest file(s) from S3.
-
Read the list of input S3 URIs.
-
Load the checkpoint (list of already processed files) from S3 (or local if we are going to upload at the end). Alternatively, we can maintain the checkpoint in S3 and update it after each file (to avoid losing progress on long runs) but then we have to handle concurrent writes if we parallelize. For single-job, we can update the checkpoint after each file and then at the end.
However, if the job fails in the middle, we want to resume from the last checkpoint. So we should update the checkpoint after each successful processing.
-
For each input file that is not in the checkpoint:
a. Download the input file (or stream it) from S3.
b. Process (score) the file.
c. Upload the output to S3 (with a known output path, e.g., same key but in a different prefix, or with a suffix).
d. Record the input file as processed in the checkpoint (append to the checkpoint file and upload to S3, or update a database).
-
At the end, we have a complete checkpoint.
But note: if we update the checkpoint after each file, we are making many S3 PUT requests. Alternatively, we can keep the checkpoint in memory and update S3 only at the end, but then if the job fails we lose progress. So we need to balance.
Option: Use a local checkpoint file and sync to S3 periodically (e.g., every N files) and at the end.
Alternatively, we can use S3 as a checkpoint by having a file that we append to. But S3 doesn't support append, so we have to download, append, and re-upload. This is inefficient and can cause race conditions if multiple processes try to update.
Given the constraints, for a singleJob we can do:
- Download the checkpoint file (if exists) at the start.
- Keep an in-memory set of processed files.
- After processing each file, add to the set and periodically (or after each) upload the updated checkpoint (by writing the entire set to a file and uploading). But if the set is large, this becomes inefficient.
Alternatively, we can use a database (like DynamoDB) for checkpoint that supports atomic updates and is scalable. But the requirement says S3 manifests, so maybe we want to stick to S3.
Another idea: Instead of a checkpoint file, we can write the output to a known location and then the existence of the output file indicates processing is done. Then we don't need a separate checkpoint. However, we must be cautious about partial writes. We can write to a temporary location and then move to the final location atomically (S3 copy and delete). But then we have to check for the existence of the output file for each input.
But then we have to list all output files to know which inputs are done? That might be inefficient if there are many.
Given the trade-offs, let's design two variants:
Variant 1 (using output existence as checkpoint):
- For each input file, compute the output S3 URI (e.g., by replacing the input prefix with output prefix).
- Check if the output file exists in S3 (by doing a head operation). If it exists, skip.
- Otherwise, process and write the output to a temporary location (e.g., with a .tmp suffix) and then move (copy and delete) to the final location.
This is idempotent and doesn't require a separate checkpoint. However, note that if the job fails after writing the temporary file but before moving, then on retry we will see the temporary file? We can design the processing to write directly to the final location only after successful processing, but then if the job fails during write, we have a partial file. So we write to temp and then atomically move.
But S3 doesn't have an atomic move. We can copy to the final location and then delete the temp. But if the job fails after copy and before delete, we have both files. Then on retry, we see the final file exists and skip, but the temp file remains. We can have a cleanup step.
Alternatively, we can write to the final location with a unique name (like input file name + timestamp) and then have a manifest of output files. But then we have to know which input corresponds to which output.
Given the complexity, let's stick to a separate checkpoint for simplicity in explanation.
Variant 2 (using a checkpoint file in S3):
Steps:
- Read the manifest (list of input URIs) from S3.
- Check if a checkpoint file exists in S3 (e.g., at a known checkpoint path). If it does, download it and parse (each line is a processed input URI).
- Create a set of processed URIs from the checkpoint.
- For each input URI in the manifest:
if input URI in processed set: skip.
else:
process the input and write output to S3 (to a determined output location).
Then, add the input URI to the processed set and update the checkpoint file (by writing the entire set to a new file and upload, or append?).
But updating the entire checkpoint file after each file is expensive. We can batch the updates: update the checkpoint file every N files or at the end. But then if the job fails, we lose the progress of the last N files.
We can do:
- Keep the checkpoint in memory and write to a local file.
- Every N files, upload the local checkpoint file to S3 (overwrite the existing checkpoint).
- At the end, upload the final checkpoint.
But if the job fails, we have the last uploaded checkpoint and then we redo at most N files.
Alternatively, we can use a log-based approach: have a checkpoint file that we append to. But S3 doesn't support append, so we have to download, append, and upload. This is even more expensive.
Given the constraints, if the number of files is not huge (say, up to 10,000) then updating the entire checkpoint every N files (where N is 100 or 1000) might be acceptable.
However, if we have millions of files, we need a better approach.
Since the requirement is for a batch scoring pipeline, let's assume the number of files is in the thousands to tens of thousands.
We can also consider using a database for checkpoint if the scale is large, but the problem says "S3 manifests", so we are expected to use S3.
Let's design for up to 100,000 files and update the checkpoint every 1000 files.
Steps:
Initialize:
- Download the manifest (list of input URIs) -> list A.
- Download the checkpoint file (if exists) -> set P of processed URIs.
- Create a set of remaining URIs: R = A - P.
Then, for each URI in R (in a loop, possibly with batching for checkpoint updates):
Process the file (download, score, upload output).
Add the URI to an in-memory set of newly processed (N) and also to P (so that if we fail in the middle, we have the updated P?).
Every 1000 files (or when we finish), we write the set P (or the entire set of processed) to a temporary checkpoint file and then upload to S3 (overwriting the old checkpoint). But note: if we are updating every 1000, then the set P is growing and we are writing the entire set each time. Alternatively, we can write only the new 1000 and then merge? But then we have to download the existing checkpoint and merge. It's simpler to write the entire set.
However, if the set P is large, writing the entire set every 1000 files becomes inefficient. We can do:
We keep two sets: P (the checkpoint we have from S3) and N (newly processed in this run).
We update the checkpoint file only at the end by writing P union N.
But then if the job fails, we lose the progress of the current run (the N set). So we need to update the checkpoint periodically.
Alternatively, we can have a checkpoint file that we append to, but by using a log file: each line is a processed URI. Then we can download the existing checkpoint, append the new ones, and upload. But then we have duplicates? We can ensure we don't process the same URI twice by checking the in-memory set (P union N). Then when we append, we are only appending new ones. But then the checkpoint file becomes a log and we have to read the entire log to know the set of processed? That's inefficient for large logs.
We can have two files:
- A set file (the entire set of processed) that we update at the end and periodically by writing the entire set.
- A log file that we append to for every processed file. Then on start, we can read the set file if exists, otherwise read the log file and build the set.
But that's more complex.
Given the trade-offs, I propose:
For simplicity and assuming the number of files is not huge (so that the entire set of processed files can be stored in memory and written to S3 every 1000 files) we do:
Let checkpoint_path = "s3://bucket/checkpoint.txt"
Let manifest_path = "s3://bucket/manifest.txt"
Steps:
1. Read manifest_path -> list of URIs (A).
2. If checkpoint_path exists, download and read into set P (each line is a URI). If not, P = empty set.
3. Let R = [uri for uri in A if uri not in P]
4. Initialize an empty set N (for new processed in this run).
5. For each uri in R:
process(uri) # download, score, write output to S3 (to a determined output path)
N.add(uri)
P.add(uri) # so that we don't process the same uri again in this run if there are duplicates in manifest? but manifest should not have duplicates.
if len(N) % 1000 == 0:
write set P to a temporary file and upload to checkpoint_path (overwrite)
6. After the loop, write set P to checkpoint_path (to make sure we have the latest).
But note: if we have duplicates in the manifest, we are adding to P and N, but we process every occurrence? We should avoid processing the same URI twice even if it appears twice in the manifest. So we use set P to track.
However, if the manifest has duplicates, we skip the duplicates because when we see the second occurrence, it will be in P (from the first occurrence). That's acceptable.
But what if the same URI appears in two different runs? We are using the same checkpoint, so we skip.
This design is idempotent.
However, note that if we update the checkpoint every 1000 files, and the job fails after processing 1500 files, then we have the checkpoint with 1000 files (the last update) and the next run will redo the next 500. That's acceptable.
But if we update every 1000, then the first 1000 are safe, the next 500 are not in the checkpoint and will be redone. That's okay because the processing is idempotent? We must ensure that processing the same input twice produces the same output and that we overwrite the output (or write to the same location). So the output must be deterministic and we must write to the same output location for the same input.
So we must design the output path deterministically from the input path.
Example:
input: s3://bucket/input/data1.json
output: s3://bucket/output/data1.json
Then if we process the same input again, we overwrite the same output. That's acceptable.
But note: if the job fails after writing the output but before updating the checkpoint, then on retry we will process again and overwrite the output. That's acceptable if the processing is deterministic.
So the pipeline is idempotent.
Now, let's write the code structure.
We'll assume we are using boto3 for S3 access.
Steps in code:
import boto3
import sys
s3 = boto3.client('s3')
def parse_s3_uri(uri):
# parse s3://bucket/key
if not uri.startswith('s3://'):
raise ValueError("Invalid S3 URI: %s" % uri)
parts = uri[5:].split('/', 1)
bucket = parts[0]
key = parts[1] if len(parts) > 1 else ''
return bucket, key
def download_manifest(manifest_uri):
bucket, key = parse_s3_uri(manifest_uri)
obj = s3.get_object(Bucket=bucket, Key=key)
content = obj['Body'].read().decode('utf-8')
uris = [line.strip() for line in content.splitlines() if line.strip()]
return uris
def download_checkpoint(checkpoint_uri):
try:
bucket, key = parse_s3_uri(checkpoint_uri)
obj = s3.get_object(Bucket=bucket, Key=key)
content = obj['Body'].read().decode('utf-8')
processed = set([line.strip() for line in content.splitlines() if line.strip()])
return processed
except s3.exceptions.NoSuchKey:
return set()
def upload_checkpoint(checkpoint_uri, processed_set):
bucket, key = parse_s3_uri(checkpoint_uri)
# Convert set to sorted list for consistency? Not necessary but might be good for debugging.
content = '\n'.join(sorted(processed_set)) + '\n'
s3.put_object(Bucket=bucket, Key=key, Body=content.encode('utf-8'))
def process_file(input_uri, output_uri):
# Download input_uri, score, and upload to output_uri.
# This function should be implemented by the user.
# It should be idempotent: if the output_uri already exists, we might skip? But we are checking the checkpoint, so we only call this for new files.
# However, we can also check if the output exists and skip? But we are using the checkpoint for that.
# So we assume that if we are in this function, the output does not exist (or we are going to overwrite).
# Steps:
# 1. Download input_uri to local temp file.
# 2. Score (call the model or whatever).
# 3. Upload the result to output_uri.
pass
def main(manifest_uri, checkpoint_uri, output_prefix):
# output_prefix is used to generate output_uri from input_uri.
# Example: if input_uri = s3://bucket/input/file1, then output_uri = s3://bucket/output_prefix/file1?
# But we need to define the mapping. Let's assume we replace the bucket's input prefix with the output prefix?
# Alternatively, we can have a function that maps input_uri to output_uri.
# For simplicity, let's assume output_uri is the same as input_uri but in a different bucket or with a different prefix.
# We can do:
# input_bucket, input_key = parse_s3_uri(input_uri)
# output_bucket = input_bucket # or a different one?
# output_key = output_prefix + input_key # if output_prefix ends with '/'
# But the problem doesn't specify. We'll let the user define the mapping in the process_file function?
# Actually, we want to generate the output_uri deterministically.
# Let's change the design: we'll have an output_base_uri (e.g., s3://bucket/output/) and then use the same key as input.
# So:
# input_uri = s3://bucket/input/path/file1
# output_uri = s3://bucket/output/path/file1
# But then we need to know the bucket. We can parse the input_uri and replace the bucket? Or use the same bucket.
# We'll assume the same bucket and just change the prefix.
# How about:
# output_uri = output_base_uri + input_key # but input_key is the key part of input_uri.
# Example:
# input_uri: s3://mybucket/input/data1.json
# output_base_uri: s3://mybucket/output/
# then output_uri: s3://mybucket/output/input/data1.json? That's not right.
# We want to replace the input prefix with output prefix?
# Let's define:
# input_prefix = "s3://bucket/input/" (the part before the file name)
# output_prefix = "s3://bucket/output/"
# Then for an input_uri, we check if it starts with input_prefix, then the relative key is input_uri[len(input_prefix):], and output_uri = output_prefix + relative_key.
# But the manifest might have URIs that are not under the same prefix? We assume all input URIs are under a common input prefix.
# Alternatively, we can just use the same key and change the bucket? The problem doesn't specify.
# Since the requirement is about S3 manifests and checkpointing, let's abstract the output mapping and let the user provide a function.
# But for the code, we need to implement something.
# Let's assume we are given an output_base_uri (s3://bucket/output/) and we use the same key as the input.
# So:
# input_uri: s3://bucket/input/file1 -> output_uri: s3://bucket/output/file1
# But note: the input_uri might have a different bucket? We'll assume same bucket.
# We can do:
# input_bucket, input_key = parse_s3_uri(input_uri)
# output_bucket = input_bucket # or we can have a separate output bucket? Let's use the same for now.
# output_key = output_prefix + input_key # but output_prefix should be just the prefix, e.g., "output/"
# Actually, output_base_uri is a full S3 URI. We can parse it and then use its bucket and key as the base.
# Let output_base_uri be like "s3://bucket/output/". Then we parse it to get output_bucket and output_key_prefix (which is "output/").
# Then for an input_uri, we get input_key and then output_key = output_key_prefix + input_key.
# But wait, if input_uri is "s3://bucket/input/file1", then input_key is "input/file1". Then output_key becomes "output/input/file1", which is not what we want.
# We want to strip the input prefix? We need to know the input prefix.
# Given the complexity, let's change the requirement: the manifest contains the input URIs and we are told the output base URI. We will use the same key (the last part of the input URI) and put it under the output base URI.
# Example:
# input_uri: s3://bucket/input/data/file1.json
# output_base_uri: s3://bucket/output/
# Then output_uri: s3://bucket/output/file1.json
# That is, we take the base name of the input key and put it in the output base.
# But then if two inputs have the same base name but different paths, they will conflict.
# Alternatively, we can use the entire key but under the output base? That would be:
# output_uri = output_base_uri + input_key
# Then for input_uri = s3://bucket/input/data/file1.json, output_uri = s3://bucket/output/input/data/file1.json.
# That's safe.
# So let's do:
# output_bucket, output_key_prefix = parse_s3_uri(output_base_uri)
# Then for each input_uri, we get input_bucket and input_key.
# We assume input_bucket == output_bucket? Not necessarily. We can have different buckets.
# But then we are writing to the output_bucket with key = output_key_prefix + input_key.
# That might not be what we want if the input_uri is from a different bucket.
# Given the time, let's assume we are using the same bucket for input and output, and we are given an output prefix (like "output/") and we use the same key.
# But wait: if the input_uri is s3://bucket1/input/file1 and output_base_uri is s3://bucket2/output/, then we want to write to bucket2 with key = output/ + file1? or output/input/file1?
# We need to decide on a mapping. Since the problem doesn't specify, let's stick to:
# output_uri = output_base_uri + input_key (where input_key is the key part of the input_uri, without the bucket).
# Example:
# input_uri: s3://bucket1/input/data/file1
# output_base_uri: s3://bucket2/output/
# Then output_uri: s3://bucket2/output/input/data/file1
# This preserves the directory structure of the input key under the output base.
# So:
output_bucket, output_key_prefix = parse_s3_uri(output_base_uri)
# output_key_prefix should end with '/'? We can ensure by adding if not.
if not output_key_prefix.endswith('/'):
output_key_prefix += '/'
Then for each input_uri:
input_bucket, input_key = parse_s3_uri(input_uri)
output_key = output_key_prefix + input_key
output_uri = f"s3://{output_bucket}/{output_key}"
But note: if the input_uri has a different bucket, we are ignoring the input_bucket and using the output_bucket. That's acceptable.
Alternatively, we can use the input_bucket as the output_bucket? We can let the user specify.
Given the time, I'll assume we are given an output_base_uri and we use that bucket and prefix.
So in the main function, we have:
manifest_uri: S3 URI of the manifest file (list of input URIs)
checkpoint_uri: S3 URI for the checkpoint file (list of processed input URIs)
output_base_uri: S3 URI for the output base (where we put the scored files)
Steps:
input_uris = download_manifest(manifest_uri)
processed = download_checkpoint(checkpoint_uri)
output_bucket, output_key_prefix = parse_s3_uri(output_base_uri)
if not output_key_prefix.endswith('/'):
output_key_prefix += '/'
new_processed = set()
for i, input_uri in enumerate(input_uris):
if input_uri in processed:
print(f"Skipping {input_uri}, already processed.")
continue
# Compute output_uri
_, input_key = parse_s3_uri(input_uri)
output_key = output_key_prefix + input_key
output_uri = f"s3://{output_bucket}/{output_key}"
# Check if output_uri already exists? We are using checkpoint, so it shouldn't. But if there's a partial run, it might.
# We can skip if output exists? But then we would add to checkpoint? That would be inconsistent because we didn't run the process.
# Alternatively, we can run the process and overwrite. But if the output exists and we skip, then we don't add to checkpoint? Then on next run we try again.
# So we should run the process and overwrite if the output exists? Or we can check and skip only if the output exists and we consider that as successful?
# But then we didn't run the process, so we don't know if the output is correct.
# Since we are using checkpoint, we trust the checkpoint. So we only skip if the input_uri is in the checkpoint.
# However, if the output exists but the input_uri is not in the checkpoint (maybe from a previous run that failed to update checkpoint), then we will process again and overwrite.
# That's acceptable because the processing is idempotent.
print(f"Processing {input_uri} -> {output_uri}")
process_file(input_uri, output_uri)
processed.add(input_uri)
new_processed.add(input_uri)
if len(new_processed) % 1000 == 0:
print(f"Updating checkpoint with {len(processed)} processed files.")
upload_checkpoint(checkpoint_uri, processed)
# Final update
upload_checkpoint(checkpoint_uri, processed)
But note: we are adding to `processed` and then uploading the entire `processed` set every 1000. That's inefficient if the set is large.
We can change to:
Let total_processed = processed (from checkpoint) union new_processed.
Then we update the checkpoint every 1000 by writing total_processed.
But total_processed grows, so we are writing a larger file each time.
Alternatively, we can append to the checkpoint file? But then we have duplicates and we have to read the entire file to get the set.
Given the scale (up to 100,000) and that we are updating every 1000, we are writing 100 times. And each time the file size grows. The last write will be 100,000 lines. That's acceptable.
But if we have 1 million files, then we are writing 1000 times and the last file is 1 million lines. That's 10MB (if each line is 100 bytes) which is acceptable.
So we'll go with this.
However, note that we are uploading the entire checkpoint after every 1000 new files. This might be slow if the checkpoint is large.
We can optimize by only uploading the new 1000 and then have the checkpoint be a concatenation of the old and new? But then we have duplicates? We can avoid duplicates by using a set.
Alternatively, we can maintain the checkpoint as a set in S3 by using a different format? We can use a database, but the requirement is S3.
Given the constraints, we'll stick to the entire set.
Code structure:
We'll have:
def main(manifest_uri, checkpoint_uri, output_base_uri):
# Step 1: Download manifest and checkpoint.
# Step 2: Determine output mapping.
# Step 3: Process each input not in checkpoint.
# Step 4: Update checkpoint periodically and at the end.
But what if the job fails in the middle? We have the checkpoint that was last uploaded (say every 1000) and then we redo the ones after that.
This is acceptable.
Now, let's write the code accordingly.
However, note: the process_file function must be implemented by the user. We'll leave it as a placeholder.
We also need to handle errors in process_file. If process_file fails for a file, we should not add it to the checkpoint and we should fail the job? Or skip and continue? The requirement doesn't specify.
We can let the user decide. We'll assume that if process_file raises an exception, we want to fail the job (so that we can fix and retry). But then we might have processed some files and then fail. Then on retry, we will skip the ones that are in the checkpoint (which includes the ones before the failure) and then try again from the failure point? But if the failure is due to a particular file, we will keep failing.
Alternatively, we can skip the file that fails and continue, but then we have to decide whether to add it to the checkpoint? We shouldn't because it failed. So we leave it out and then on the next run, we try again.
But then if the failure is transient, we might succeed on retry. So we should not add to checkpoint until success.
So in the loop:
try:
process_file(...)
processed.add(uri)
new_processed.add(uri)
except Exception as e:
print(f"Failed to process {uri}: {e}")
# We don't add to processed, so we will retry next time.
# But we might want to break? or continue?
# Let's continue so that we process other files, but then the job will end with an error?
# We can collect the failures and then at the end, if there are failures, exit with error.
We can do:
failures = []
for uri in R:
try:
process_file(...)
processed.add(uri)
new_processed.add(uri)
except Exception as e:
failures.append( (uri, str(e)) )
Then at the end, if failures:
print("Failures:", failures)
sys.exit(1)
But then we have processed some files and then failed. The checkpoint has been updated for the successful ones. On retry, we will skip the successful ones and try the failed ones again.
That's acceptable.
Now, let's code accordingly.
However, note: if we are updating the checkpoint every 1000, then the successful ones are already in the checkpoint (periodic update) and the ones that failed are not. So on retry, we will try the failed ones again.
But what if the job fails during the periodic update? Then the checkpoint might not have the last 1000? Actually, we update every 1000 new files, so if we have 1500 new files and we update at 1000 and then at 2000 (but we only have 1500, so we update at 1500 at the end). So if we fail at 1500, we have updated at 1000 and then the last 500 are not in the checkpoint. Then on retry, we will redo the last 500. That's acceptable.
But note: the set processed is updated in memory for every successful file, so if we fail at 1500, the in-memory set has 1500, but the checkpoint on S3 only has 1000. Then on retry, we download the checkpoint (1000) and then we will process the 500 again (because they are not in the checkpoint). But we already processed them in the previous run? No, because we didn't update the checkpoint for the last 500. So we redo the last 500. That's acceptable.
However, if the job fails after processing 1500 and we updated the checkpoint at 1000 and then at 1500 (at the end) but the upload of the checkpoint at 1500 fails? Then we have the checkpoint with 1000 and we lose the 500? Actually, we update the checkpoint every 1000 and at the end. So if we fail at 1500 and the final update fails, then the checkpoint remains at 1000. Then on retry, we redo 500. That's acceptable.
But what if the job fails during the periodic update? Then we might have uploaded a checkpoint that is incomplete? We are writing the entire set processed (which at that point includes the 1000 we just processed). So if we update every 1000, then at the 1000th file, we upload the set of 1000 (plus the ones from the initial checkpoint). That's correct.
So the design is sound.
Let's code accordingly.
We'll also add a parameter for the checkpoint update frequency.
Code:
We assume the manifest file is a list of S3 URIs, one per line.
We'll write the checkpoint as a list of S3 URIs, one per line.
We'll use:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--manifest-uri', required=True)
parser.add_argument('--checkpoint-uri', required=True)
parser.add_argument('--output-base-uri', required=True)
parser.add_argument('--checkpoint-frequency', type=int, default=1000)
Then in the loop, we check if len(new_processed) % checkpoint_frequency == 0.
But note: new_processed is the set of processed in this run. We want to update the checkpoint every checkpoint_frequency new files, regardless of the total.
We can do:
if len(new_processed) % checkpoint_frequency == 0:
upload_checkpoint(checkpoint_uri, processed)
But note: at the beginning, new_processed is empty, so we don't update until we have at least checkpoint_frequency.
We can also update at the end.
Let's code accordingly.
However, note: the set processed is the union of the initial checkpoint and the new_processed. So when we upload, we are uploading the entire set.
Now, let's write the code.
We'll also handle the case where the output_base_uri does not have a trailing slash.
We'll also make sure to handle errors in downloading the manifest and checkpoint.
Let's code accordingly.
We'll also consider that the manifest might be large, so we might want to stream it? But for simplicity, we download the entire manifest.
If the manifest is huge (millions of lines) then we might run out of memory. We can process the manifest line by line, but then we need to have the checkpoint in memory anyway. So we assume the manifest fits in memory.
Similarly, the checkpoint (set of processed) must fit in memory.
Now, the code:
Note: This is a single-threaded, single-process design.
For distributed processing, we would need a shared checkpoint (like DynamoDB) and each worker would update the checkpoint atomically. But that's out of scope.
Let's write the code accordingly.
We'll also add logging.
We'll write the process_file function as a placeholder that the user must implement.
Alternatively, we can make the scoring function a separate script or module. But for simplicity, we'll assume the user will edit the code.
We can also make the process_file a command line argument (a separate script) but that's more complex.
Given the time, we'll leave it as a function to be implemented.
Now, the code:
I'll design a robust batch scoring pipeline with idempotent orchestration, S3-based manifests, and checkpointing. This solution uses Python with AWS services (S3, DynamoDB for checkpointing) and can be orchestrated via AWS Step Functions or Airflow.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Input Data │───▶│ S3 Manifest(s) │───▶│ Job Orchestrator│
│ (S3 Files) │ │ (list of URIs) │ │ (Step Functions)│
└─────────────────┘ └──────────────────┘ └────────┬────────┘
│
┌─────────────────┐ ┌──────────────────┐ ┌────────▼────────┐
│ Output Scores │◀───│ Checkpoint DB │◀───│ Scoring Worker │
│ (S3) │ │ (DynamoDB) │ │ (Lambda/EMR) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
Core Components
1. S3 Manifest Structure
Manifest files contain lists of input S3 URIs to process:
{
"manifest_id": "batch_20240101_001",
"created_at": "2024-01-01T00:00:00Z",
"input_prefix": "s3://bucket/raw-data/",
"files": [
"s3://bucket/raw-data/file1.parquet",
"s3://bucket/raw-data/file2.parquet",
...
],
"total_files": 1000,
"status": "PENDING"
}
Manifest Types:
- Pending Manifest:
s3://bucket/manifests/pending/batch_*.json
- Processing Manifest:
s3://bucket/manifests/processing/batch_*.json
- Completed Manifest:
s3://bucket/manifests/completed/batch_*.json
- Failed Manifest:
s3://bucket/manifests/failed/batch_*.json
2. Checkpointing with DynamoDB
# DynamoDB Table: BatchScoringCheckpoints
{
"manifest_id": "batch_20240101_001", # Partition key
"file_uri": "s3://bucket/raw-data/file1.parquet", # Sort key
"status": "SUCCESS|FAILED|SKIPPED",
"processed_at": "2024-01-01T12:00:00Z",
"output_uri": "s3://bucket/scored/file1.parquet",
"retry_count": 0,
"error_message": null,
"worker_id": "lambda-123",
"checksum": "sha256:abc123" # Input file checksum for validation
}
GSI for queries:
status GSI: Query by status (SUCCESS, FAILED)
processed_at GSI: Time-based queries
3. Idempotent Orchestrator (AWS Step Functions)
{
"Comment": "Batch Scoring Pipeline",
"StartAt": "ValidateManifest",
"States": {
"ValidateManifest": {
"Type": "Task",
"Resource": "arn:aws:lambda:region:account:function:validate-manifest",
"Next": "InitializeCheckpoint"
},
"InitializeCheckpoint": {
"Type": "Task",
"Resource": "arn:aws:lambda:region:account:function:init-checkpoint",
"Next": "ProcessFilesMap"
},
"ProcessFilesMap": {
"Type": "Map",
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "CheckAndProcessFile",
"States": {
"CheckAndProcessFile": {
"Type": "Task",
"Resource": "arn:aws:lambda:region:account:function:process-file",
"Retry": [
{
"ErrorEquals": ["S3.ReadError", "ProcessingError"],
"IntervalSeconds": 30,
"MaxAttempts": 3,
"BackoffRate": 2
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Next": "FileFailed"
}
],
"Next": "FileSucceeded"
},
"FileSucceeded": {
"Type": "Succeed"
},
"FileFailed": {
"Type": "Fail",
"Error": "FileProcessingFailed",
"Cause": "File processing failed after retries"
}
}
},
"ItemsPath": "$.files_to_process",
"MaxConcurrency": 100,
"Next": "FinalizeManifest"
},
"FinalizeManifest": {
"Type": "Task",
"Resource": "arn:aws:lambda:region:account:function:finalize-manifest",
"End": true
}
}
}
4. Scoring Worker Implementation
import json
import boto3
import hashlib
from datetime import datetime
from typing import Dict, Any, Optional
s3 = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
checkpoint_table = dynamodb.Table('BatchScoringCheckpoints')
class IdempotentScorer:
def __init__(self, model_path: str):
self.model = self.load_model(model_path)
def load_model(self, path: str):
# Load ML model (from S3 or container)
pass
def compute_checksum(self, bucket: str, key: str) -> str:
"""Compute SHA256 checksum of S3 object"""
obj = s3.get_object(Bucket=bucket, Key=key)
content = obj['Body'].read()
return hashlib.sha256(content).hexdigest()
def should_process(self, manifest_id: str, file_uri: str, expected_checksum: str) -> bool:
"""Check if file needs processing (idempotency check)"""
try:
response = checkpoint_table.get_item(
Key={'manifest_id': manifest_id, 'file_uri': file_uri}
)
item = response.get('Item')
if not item:
return True
# Check if checksum matches (detects input changes)
if item.get('checksum') != expected_checksum:
return True
# Check if output exists
if item['status'] == 'SUCCESS':
try:
s3.head_object(Bucket=item['output_bucket'], Key=item['output_key'])
return False # Already processed successfully
except s3.exceptions.NoSuchKey:
# Output was deleted, need to reprocess
return True
return item['status'] in ['FAILED', 'SKIPPED']
except Exception as e:
print(f"Checkpoint check failed: {e}")
return True # Fail safe: process if uncertain
def mark_checkpoint(self,
manifest_id: str,
file_uri: str,
status: str,
output_uri: Optional[str] = None,
error: Optional[str] = None,
checksum: str = None):
"""Update checkpoint in DynamoDB"""
item = {
'manifest_id': manifest_id,
'file_uri': file_uri,
'status': status,
'processed_at': datetime.utcnow().isoformat(),
'retry_count': 0 # Could increment on retries
}
if output_uri:
bucket, key = self.parse_s3_uri(output_uri)
item.update({
'output_uri': output_uri,
'output_bucket': bucket,
'output_key': key
})
if error:
item['error_message'] = error[:400] # Truncate long errors
if checksum:
item['checksum'] = checksum
checkpoint_table.put_item(Item=item)
def process_file(self,
manifest_id: str,
input_uri: str,
output_base_uri: str) -> Dict[str, Any]:
"""Main processing function with checkpointing"""
# Parse URIs
input_bucket, input_key = self.parse_s3_uri(input_uri)
output_bucket, output_prefix = self.parse_s3_uri(output_base_uri)
output_key = f"{output_prefix.rstrip('/')}/{input_key.split('/')[-1]}"
output_uri = f"s3://{output_bucket}/{output_key}"
# Compute checksum for idempotency
checksum = self.compute_checksum(input_bucket, input_key)
# Check if already processed
if not self.should_process(manifest_id, input_uri, checksum):
print(f"Skipping {input_uri} - already processed")
return {'status': 'SKIPPED', 'output_uri': output_uri}
try:
# Download and process
obj = s3.get_object(Bucket=input_bucket, Key=input_key)
data = obj['Body'].read()
# Your scoring logic here
scored_data = self.score(data)
# Upload with server-side encryption
s3.put_object(
Bucket=output_bucket,
Key=output_key,
Body=scored_data,
ServerSideEncryption='AES256'
)
# Mark success
self.mark_checkpoint(
manifest_id=manifest_id,
file_uri=input_uri,
status='SUCCESS',
output_uri=output_uri,
checksum=checksum
)
return {'status': 'SUCCESS', 'output_uri': output_uri}
except Exception as e:
error_msg = str(e)[:400]
self.mark_checkpoint(
manifest_id=manifest_id,
file_uri=input_uri,
status='FAILED',
error=error_msg,
checksum=checksum
)
raise
def parse_s3_uri(self, uri: str) -> tuple:
"""Parse s3://bucket/key into (bucket, key)"""
if not uri.startswith('s3://'):
raise ValueError(f"Invalid S3 URI: {uri}")
parts = uri[5:].split('/', 1)
return parts[0], parts[1] if len(parts) > 1 else ''
def score(self, data: bytes) -> bytes:
"""Implement your scoring logic"""
# Example: return data.upper() if text, or apply ML model
pass
# Lambda handler
def lambda_handler(event, context):
scorer = IdempotentScorer(model_path=event['model_path'])
results = []
for file_uri in event['files']:
try:
result = scorer.process_file(
manifest_id=event['manifest_id'],
input_uri=file_uri,
output_base_uri=event['output_base_uri']
)
results.append(result)
except Exception as e:
results.append({
'file_uri': file_uri,
'status': 'FAILED',
'error': str(e)
})
return {
'manifest_id': event['manifest_id'],
'total': len(results),
'success': sum(1 for r in results if r['status'] == 'SUCCESS'),
'failed': sum(1 for r in results if r['status'] == 'FAILED'),
'skipped': sum(1 for r in results if r['status'] == 'SKIPPED')
}
5. Manifest Manager Lambda
def validate_manifest(manifest_uri: str) -> Dict:
"""Validate manifest structure and S3 access"""
bucket, key = parse_s3_uri(manifest_uri)
obj = s3.get_object(Bucket=bucket, Key=key)
manifest = json.loads(obj['Body'].read())
required_fields = ['manifest_id', 'files', 'input_prefix']
for field in required_fields:
if field not in manifest:
raise ValueError(f"Missing required field: {field}")
# Validate each file exists
for file_uri in manifest['files']:
try:
b, k = parse_s3_uri(file_uri)
s3.head_object(Bucket=b, Key=k)
except Exception as e:
raise ValueError(f"File not accessible: {file_uri} - {e}")
return manifest
def move_manifest(manifest_uri: str, status: str):
"""Move manifest between status directories"""
bucket, key = parse_s3_uri(manifest_uri)
new_key = key.replace('/manifests/pending/', f'/manifests/{status}/')
s3.copy_object(
Bucket=bucket,
CopySource={'Bucket': bucket, 'Key': key},
Key=new_key
)
s3.delete_object(Bucket=bucket, Key=key)
6. Orchestration Script (Alternative: Airflow DAG)
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'data-engineering',
'depends_on_past': False,
'start_date': datetime(2024, 1, 1),
'retries': 2,
'retry_delay': timedelta(minutes=5)
}
dag = DAG(
'batch_scoring_pipeline',
default_args=default_args,
schedule_interval=None, # Trigger manually
catchup=False
)
def discover_manifests(**context):
"""Find pending manifests in S3"""
pending_manifests = s3.list_objects_v2(
Bucket='my-bucket',
Prefix='manifests/pending/'
).get('Contents', [])
manifests = []
for obj in pending_manifests:
if obj['Key'].endswith('.json'):
manifests.append(f"s3://my-bucket/{obj['Key']}")
context['ti'].xcom_push(key='manifests', value=manifests)
def process_manifest(manifest_uri: str, **context):
"""Process a single manifest via Step Functions"""
sf = boto3.client('stepfunctions')
execution_name = f"score-{manifest_uri.split('/')[-1].replace('.json', '')}"
sf.start_execution(
stateMachineArn='arn:aws:states:region:account:stateMachine:batch-scoring',
name=execution_name,
input=json.dumps({
'manifest_uri': manifest_uri,
'output_base_uri': 's3://my-bucket/scored/',
'model_path': 's3://my-bucket/models/model.pkl'
})
)
# Wait for execution to complete (or use callback pattern)
return execution_name
# Task definitions
t1 = PythonOperator(
task_id='discover_manifests',
python_callable=discover_manifests,
dag=dag
)
t2 = PythonOperator.partial(
task_id='process_manifest',
python_callable=process_manifest,
dag=dag
).expand(manifest_uri="{{ ti.xcom_pull(task_ids='discover_manifests', key='manifests') }}")
t1 >> t2
7. Monitoring & Alerting
# CloudWatch Metrics to monitor:
# 1. FilesProcessed
# 2. FilesFailed
# 3. ProcessingDuration
# 4. CheckpointRead/WriteLatency
# CloudWatch Alarms:
# - FilesFailed > threshold for 5 minutes
# - PipelineDuration > SLA
# - DynamoDB Throttling
# SNS Topic for failures:
# - Manifest validation failures
# - Step Function failures
# - Lambda errors > threshold
8. Retry & Recovery Strategies
Automatic Retries:
- Lambda: Configured in Step Functions (exponential backoff)
- EMR: Controlled by
Retry policy in Step Functions
Manual Recovery:
# Reprocess failed files from checkpoint table
aws dynamodb query \
--table-name BatchScoringCheckpoints \
--index-name status-index \
--key-condition-expression "manifest_id = :mid AND #status = :status" \
--expression-attribute-values '{":mid": {"S": "batch_20240101_001"}, ":status": {"S": "FAILED"}}' \
--projection-expression "file_uri" \
--output json | jq -r '.Items[].file_uri.S' > failed_files.txt
# Create new manifest from failed files and reprocess
9. Deployment & IaC (CloudFormation/CDK)
# CloudFormation snippet
Resources:
CheckpointTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: BatchScoringCheckpoints
AttributeDefinitions:
- AttributeName: manifest_id
AttributeType: S
- AttributeName: file_uri
AttributeType: S
KeySchema:
- AttributeName: manifest_id
KeyType: HASH
- AttributeName: file_uri
KeyType: RANGE
GlobalSecondaryIndexes:
- IndexName: status-index
KeySchema:
- AttributeName: status
KeyType: HASH
Projection:
ProjectionType: ALL
BillingMode: PAY_PER_REQUEST
Key Idempotency Guarantees
-
Exactly-Once Processing:
- DynamoDB conditional writes (
ConditionExpression)
- Manifest status transitions (PENDING → PROCESSING → COMPLETED/FAILED)
- Output file atomic writes (S3
put_object overwrites)
-
Checkpoint Completeness:
- All successful writes update DynamoDB
- Failed files remain in
FAILED status for reprocessing
- Manifest state matches DynamoDB counts
-
Recovery:
- Job can resume from any point using checkpoint
- Manual reprocessing of failed files via query
- Manifest archival for audit trail
Cost Optimization
-
Lambda Workers:
- Set memory based on model size
- Use Provisioned Concurrency for steady-state
- Batch multiple files in one invocation (up to 10 MB payload)
-
S3:
- Use Intelligent-Tiering for output
- Lifecycle policies for old manifests
- S3 Inventory for large manifest discovery
-
DynamoDB:
- On-demand capacity for spiky workloads
- TTL for old checkpoints (e.g., 90 days)
- GSIs only if needed
Testing Strategy
- Unit Tests: Idempotency logic, checksum calculation
- Integration Tests:
- End-to-end with sample manifests
- Failure injection (S3 errors, Lambda timeouts)
- Concurrent manifest processing
- Chaos Testing:
- Kill workers mid-processing
- Corrupt checkpoint entries
- Network partitions
Alternative for Very Large Scale (10M+ files)
For massive scale, consider:
- S3 Inventory + Athena for manifest generation
- SQS + Lambda instead of Step Functions Map state
- DynamoDB Streams for checkpoint aggregation
- EMR/Spark for distributed processing with checkpointing to S3
This design provides strong idempotency, observability, and cost-effective scaling while leveraging managed AWS services for reliability.