Serverless Data Processing Pipeline Architecture
As Sherlock, I'll architect a scalable, cost-effective serverless data processing pipeline using AWS services (adaptable to GCP/Azure equivalents). This design processes streaming/batch data (e.g., JSON logs or CSV files) from ingestion to storage/analytics, emphasizing fault-tolerance, observability, and automation.
High-Level Architecture (Text Diagram)
Event Sources
├── S3 Bucket (Batch: file upload)
├── Kinesis Data Stream (Streaming: real-time events)
└── EventBridge (Scheduling/Cross-service events)
↓ (Triggers)
Amazon EventBridge (Event Bus for fan-out/routing)
↓
AWS Step Functions (Orchestrator: Stateful Workflow)
├── Stateless Stages (Lambdas: Validate → Transform → Enrich)
├── Stateful Stages (DynamoDB/S3 for aggregation/checkpoints)
└── Parallel/Map States for scalability
↓ (Outputs/Errors)
├── S3 Data Lake (Processed output)
├── DynamoDB (Stateful storage/index)
├── DLQ (SQS for retries/errors)
└── Notifications (SNS)
Observability: CloudWatch + X-Ray
Cost Controls: Budgets + Lambda optimizations
IaC: Terraform/CDK + GitHub Actions
1. Event Sources
- Batch Processing: S3 Event Notifications (e.g.,
ObjectCreated) trigger EventBridge for file uploads (CSV/JSON/Parquet up to GBs).
- Streaming: Kinesis Data Streams/Shards for high-velocity data (e.g., IoT logs). Use Kinesis Data Firehose for buffering/direct S3 delivery.
- Scheduled/External: EventBridge Scheduler (cron jobs) or API Gateway (HTTP POST for ad-hoc ingestion).
- Fan-out: EventBridge rules route to multiple targets (e.g., start Step Functions, notify Slack).
- Why? Decouples sources; auto-scales to 1000s TPS.
2. Function Orchestration
- Core: AWS Step Functions (Express for <5min workflows, Standard for long-running).
- States:
| State Type | Purpose | Example |
|---|
| Task (Lambda) | Stateless processing | Validate data schema |
| Parallel/Map | Fan-out | Transform shards in parallel |
| Choice | Conditional routing | If valid → Enrich; else → DLQ |
| Wait | Throttling/delays | Rate-limit external APIs |
- Why Step Functions? Visual DSL (ASL JSON), built-in retries/timeouts, execution history (14d free), integrates natively with 200+ services. No custom orchestration code.
- Execution: EventBridge → Step Functions StartExecution (input:
{ "eventId": "...", "dataBucket": "s3://..." }).
3. Stateless vs Stateful Stages
- Stateless Stages (90% of pipeline: Pure functions, idempotent):
| Stage | Lambda Runtime | Input/Output | Runtimes |
|---|
| Validate | Python/Node.js | S3/Kinesis → Temp S3 | 15s, 512MB |
| Transform | Python (Pandas/Dask) | Temp S3 → Temp S3 | 5min, 10GB (ARM64) |
| Enrich | Node.js | Temp S3 + External API → Final S3 | 30s, 1GB |
- Traits: No shared memory; use S3 for intermediates. Idempotent via event IDs/checksums.
- Stateful Stages (Coordination/aggregation):
| Stage | Service | Purpose |
|---|
| Aggregation | DynamoDB (TTL table) | Dedup/merge batches (e.g., session state) |
| Checkpointing | S3 + DynamoDB | Track offsets (Kinesis shards), resume on failure |
| Final Merge | Step Functions Callback | Wait for all parallels, then store |
- Traits: DynamoDB for low-latency reads/writes (<1ms, $0.25/GB); S3 for durable blobs. Use optimistic locking (conditional writes).
- Transition: Stateless → Stateful via Step Functions Pass state (JSON payloads <256KB; use S3 for larger).
4. Error Handling and Retries
- Lambda Level:
- Timeouts: 15s-15min based on stage.
- Retries: Disabled (handle in orchestrator).
- DLQ: SQS (Redrive → Step Functions retry).
- Step Functions Level:
"Retry": [{
"ErrorEquals": ["States.ALL"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2.0
}],
"Catch": [{
"ErrorEquals": ["States.ALL"],
"Next": "DeadLetterState",
"ResultPath": "$.error"
}]
- Exponential backoff; max 4,096 retries.
- DeadLetterState → SNS → PagerDuty + S3 log dump.
- Idempotency: Event IDs + DynamoDB (unique constraint).
- Chaos Handling: Kinesis enhanced fan-out; Step Functions Task Tokens for async callbacks.
5. Cost Controls
- Estimates (1M events/day, 1KB/event):
| Service | Monthly Cost | Optimization |
|---|
| Lambda | $10-50 | ARM64 (20% savings), Powertools warm starts |
| Step Functions | $5 | Express for short jobs |
| Kinesis/S3 | $20-100 | Firehose buffering, S3 Intelligent-Tiering |
| DynamoDB | $10 | On-Demand + TTL |
| Total | <$200 | - |
- Guards:
- AWS Budgets ($ threshold → SNS).
- Lambda Reserved Concurrency (e.g., 1000 total).
- S3 Lifecycle: Delete temps after 1d.
- EventBridge: Throttling rules.
- Monitoring: CloudWatch Anomaly Detection on costs.
6. Observability
- Logs: Lambda → CloudWatch Logs (structured JSON via Powertools).
- Traces: AWS X-Ray (auto-instrument Lambdas/Step Functions; service map).
- Metrics:
| Custom Metric | Emitted Via | Alert On |
|---|
| Processing Latency | CloudWatch Embedded Metric | >95th %ile |
| Error Rate | Lambda Metrics | >1% |
| Throughput | Kinesis GetRecords | Dropped shards |
- Dashboards: CloudWatch + Grafana OSS.
- Debugging: Step Functions execution graph; X-Ray traces (end-to-end).
- Auditing: CloudTrail for API calls.
7. IaC/CI-CD Integration
- IaC: AWS CDK (TypeScript/Python) for everything (declarative, type-safe).
// cdk-stack.ts excerpt
const pipeline = new sfn.StateMachine(this, 'DataPipeline', {
definition: processStateMachine,
stateMachineType: sfn.StateMachineType.STANDARD,
});
- Alternatives: Terraform (modules for reuse), Serverless Framework.
- CI-CD:
| Tool | Flow |
|---|
| GitHub Actions | PR → Lint/Test → Synth → Deploy (cdk deploy) |
| AWS CodePipeline | GitHub → CDK Synth → Manual Approval → Deploy to prod |
- Stages:
cdk diff (preview), tagging (env-specific stacks).
- Secrets: SSM Parameter Store/AWS Secrets Manager.
- Blue/Green: CDK Custom Resources for zero-downtime (Step Functions versioning).
- Best Practice: Monorepo; envs via CDK context (
dev/prod).
Deployment & Next Steps
- Clone a CDK starter:
npx cdk init app --language typescript.
- Define Step Functions ASL in CDK.
- Test:
sam local invoke for Lambdas; Step Functions Local.
- Scale: Auto-adjust Kinesis shards via metrics.
This pipeline handles 1-10k events/sec at <1% error rate, under $0.20/M events. Adapt for GCP (Cloud Functions + Workflows + Pub/Sub) or Azure (Functions + Logic Apps + Event Grid). Questions on specifics?