Designing a High-Volume TMDB Web Scraper with AWS Step Functions
To design an efficient system for scraping millions of records from TMDB using AWS Lambda and Step Functions, we'll need to carefully architect the workflow to balance performance and cost. Here's a comprehensive design:
System Architecture Overview
- Harvester Lambda: Downloads and processes TMDB's daily ID exports
- Collector Lambda: Fetches detailed records for given IDs
- Step Function Orchestration: Combines Standard and Express workflows for optimal cost/performance
Step Function Design
1. Main Workflow (Standard Step Function)
This will be our primary orchestrator with a longer timeout (up to 1 year) and better error handling.
{
"Comment": "TMDB Scraper Main Workflow",
"StartAt": "InitializeScrapingJob",
"States": {
"InitializeScrapingJob": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "harvester-lambda",
"Payload": {
"datasetName.$": "$.datasetName",
"jobId.$": "$.jobId"
}
},
"Next": "ProcessDatasetIds",
"ResultPath": "$.harvesterResult"
},
"ProcessDatasetIds": {
"Type": "Map",
"ItemsPath": "$.harvesterResult.ids",
"MaxConcurrency": 100,
"Iterator": {
"StartAt": "BatchProcessing",
"States": {
"BatchProcessing": {
"Type": "Task",
"Resource": "arn:aws:states:::states:startExecution.sync:2",
"Parameters": {
"StateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:CollectorExpressWorkflow",
"Input": {
"ids.$": "$",
"jobId.$": "$.jobId",
"batchSize": 100
}
},
"End": true
}
}
},
"Next": "FinalizeJob",
"ResultPath": "$.collectionResults"
},
"FinalizeJob": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "finalizer-lambda",
"Payload": {
"jobId.$": "$.jobId",
"results.$": "$.collectionResults"
}
},
"End": true
}
}
}
2. Collector Express Workflow (Express Step Function)
This will handle the actual data collection with lower cost and higher throughput.
{
"Comment": "TMDB Collector Express Workflow",
"StartAt": "ProcessBatch",
"States": {
"ProcessBatch": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "collector-lambda",
"Payload": {
"ids.$": "$.ids",
"jobId.$": "$.jobId"
}
},
"Next": "CheckForMore",
"ResultPath": "$.batchResult"
},
"CheckForMore": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.batchResult.hasMore",
"BooleanEquals": true,
"Next": "ProcessBatch"
}
],
"Default": "Complete"
},
"Complete": {
"Type": "Succeed"
}
}
}
Implementation Details
1. Harvester Lambda Function
import boto3
import requests
import zipfile
import io
import json
s3 = boto3.client('s3')
def lambda_handler(event, context):
dataset_name = event['datasetName']
job_id = event['jobId']
# Download the ZIP file from TMDB
url = f"https://files.tmdb.org/p/exports/{dataset_name}_ids_*.json.gz"
response = requests.get(url)
response.raise_for_status()
# Process the ZIP file
with zipfile.ZipFile(io.BytesIO(response.content)) as zip_file:
# Extract and process the JSON file
with zip_file.open(zip_file.namelist()[0]) as json_file:
ids = json.load(json_file)
# Store the IDs in S3 for reference
s3.put_object(
Bucket="tmdb-scraper-ids",
Key=f"{job_id}/{dataset_name}.json",
Body=json.dumps(ids)
)
# Return the IDs for processing
return {
'jobId': job_id,
'datasetName': dataset_name,
'ids': ids
}
2. Collector Lambda Function
import boto3
import requests
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('TMDB_Records')
def lambda_handler(event, context):
ids = event['ids']
job_id = event['jobId']
batch_size = event.get('batchSize', 100)
results = []
for i in range(0, len(ids), batch_size):
batch = ids[i:i + batch_size]
# Process each ID in the batch
for tmdb_id in batch:
try:
# Fetch data from TMDB API
response = requests.get(
f"https://api.themoviedb.org/3/{event['datasetName']}/{tmdb_id}",
params={'api_key': 'YOUR_API_KEY'}
)
response.raise_for_status()
data = response.json()
# Store in DynamoDB
table.put_item(
Item={
'id': tmdb_id,
'data': data,
'dataset': event['datasetName'],
'jobId': job_id,
'timestamp': int(time.time())
}
)
results.append({
'id': tmdb_id,
'status': 'success'
})
except Exception as e:
results.append({
'id': tmdb_id,
'status': 'failed',
'error': str(e)
})
return {
'processed': len(results),
'successful': len([r for r in results if r['status'] == 'success']),
'failed': len([r for r in results if r['status'] == 'failed']),
'hasMore': len(ids) > (i + batch_size)
}
Cost Optimization Strategies
-
Express Workflows for Collector: Using Express Step Functions for the collector workflow reduces cost significantly for high-volume processing.
-
Batch Processing: Processing IDs in batches (e.g., 100 at a time) reduces the number of Lambda invocations.
-
Concurrency Control: The Map state in the main workflow controls how many parallel batches are processed.
-
Error Handling: Implement retry logic in the collector Lambda for transient failures.
-
Data Storage: Use DynamoDB for its scalability and pay-per-request pricing model.
Deployment Considerations
-
Lambda Configuration:
- Harvester: 1024MB memory, 15-minute timeout
- Collector: 512MB memory, 5-minute timeout
-
Step Function Configuration:
- Main Workflow: Standard type
- Collector Workflow: Express type with 5-minute timeout
-
Monitoring:
- CloudWatch Alarms for failed executions
- Custom metrics for tracking progress
-
Scaling:
- Consider using SQS between steps if you need to handle very large datasets
- Implement checkpointing for long-running jobs
Alternative Approach for Very Large Datasets
If you're dealing with tens of millions of records, consider this modified approach:
- Harvester writes IDs to S3 in chunks
- S3 Event Notifications trigger the collector workflow
- Collector processes each chunk file independently
- Finalizer aggregates results from all chunks
This approach can be more cost-effective for extremely large datasets as it leverages S3's scalability and event-driven architecture.
Would you like me to elaborate on any specific part of this design or provide additional implementation details?