SCIP — Smart Supply Chain Intelligence Platform
Production-grade AWS-native data platform for a food-tech supply chain: Food Suppliers → Warehouses → Distribution Centers → Restaurants. Built as a comprehensive AWS Certified Data Engineer (DEA-C01) reference architecture. Region: ap-south-1 · Budget: ~$143/mo continuous, ~$70/mo dev mode.
Business Questions Answered
Which suppliers are missing delivery SLAs? — Supplier Scorecard mart, 4-hr refresh. Score = OTD 40% + fill_rate 30% + quality 20% + lead_time 10%. Alert when score < 70.
Which warehouses face stockout in 7 days? — Inventory Health mart + ML forecast. days_of_supply computed from avg_daily_consumption via lag window.
Predicted demand per SKU per region for 30 days — SageMaker XGBoost quantile regression. Returns p10/p50/p90 confidence intervals.
What does the SOP say about cold chain breaches? — Bedrock Agent with RAG over S3 knowledge base. Claude Sonnet 4.6, 4 action groups.
Which shipments are delayed and by how much? — DynamoDB shipments_live, <1s latency. delay_days field (negative = early).
End-to-End Architecture
binlog_format=ROW · binlog_row_image=FULL
gtid_mode=ON · log_bin_trust_functions=1
Database:
scip_erpTables: suppliers_master, products_master,
purchase_orders (2700 rows), order_lines (13500 rows)
Credentials → Secrets Manager (30-day rotation)
·
shipment_update — 20/min (Markov chain: CREATED→PICKED→IN_TRANSIT→DELIVERED/EXCEPTION)·
inventory_change — 10/min (qty deltas, low_stock_flag)·
sensor_reading — 5/min (temperature_c, humidity_pct, lat/lng, is_breach)Avro BACKWARD_TRANSITIVE
Product JSON: sku, category_l1/l2/l3, unit_cost_inr, shelf_life_days, cold_chain specs
Inventory snapshots: warehouse_id, product_id, qty_on_hand, qty_reserved, reorder_point
S3 event → Lambda: batch_file_validator → /raw/ or /quarantine/
3 Avro schemas registered:
· shipment_update
· inventory_change
· sensor_reading
Schema ID injected in Kinesis record header
Consumers validate on read
Type: full-load-and-cdc
Source: MySQL (scip_erp.%)
Target: S3 endpoint
Full load:
/raw/dms/scip_erp/{table}/LOAD*.csv.gzCDC:
/raw/dms/cdc/{table}/yyyy/mm/dd/32KB flush / 60s max batch interval
GZIP CSV output
POST /events → Lambda: event_ingest → KDS
Kinesis Data Streams: ON_DEMAND (0→200 shards auto), 24h retention, SSE-KMS
Enhanced Fan-Out consumer for Flink (2 MB/s dedicated)
Firehose: KDS source → JQ dynamic partitioning by event_type → S3 /raw/events/{event_type}/YYYY/MM/DD/ · GZIP · 5 min/64 MB buffer
Validates Avro schema via Glue Schema Registry
DESTINATION_TYPE env var: S3 (Phase 1) → KDS (Phase 2+)Writes pipeline lineage to DynamoDB
Triggered: API Gateway POST /events
Logs: JSON structured ·
SCIP/Stream CloudWatch namespaceValidates CSV/JSON schema (completeness, non-negative, enum containment)
VALID → promotes to
/raw/{entity}/INVALID →
/quarantine/ + SNS dq-alertsWrites lineage row to DynamoDB pipeline_lineage
DQ (1 job): dq_validator — completeness, uniqueness, schema, freshness, referential integrity, non-negative, enum, temperature range checks → JSON reports to /dq-results/ · fail if pass_rate < 95%
Curated (5 jobs): SCD Type 2 on suppliers, orders, products, shipments, inventory → active snapshot + history/ + redshift/ subpaths
Mart (4 jobs): delivery_performance, inventory_health, supplier_scorecard (composite 0–100 score), demand_forecast_prep → Parquet ZSTD
Trigger: EventBridge
cron(0 */4 * * ? *)FormatInput → RecordPipelineStart → ValidateIncomingFiles → RunDQValidator → StagingTransforms (Parallel 6) → CuratedTransforms (Parallel 4) → ShipmentsToCurated → MartAggregations (Parallel 4) → StartCrawlers → WaitForCrawlers (poll loop) → LoadRedshift → RefreshQuickSight → RecordPipelineComplete
Every state: Catch ALL → PipelineFailed → SNS
Source: KDS Enhanced Fan-Out consumer
Pipeline: parse JSON → filter shipment_update → keyBy(status) → 5-min TumblingProcessingTimeWindows → StatusWindowAggregator (count) → DynamoDB otd-metrics
Auth: SigV4 via stdlib urllib (zero external deps)
Credential chain: env vars → STS → IMDSv2
Special: /incoming/ (expire 30d), /quarantine/ (expire 30d), /dq-results/ (expire 90d), /knowledge-base/ (no lifecycle), /audit-logs/ (1yr→GLACIER_IR)
SSE-S3 · DenyNonHTTPS bucket policy · Naming:
scip-{env}-{zone}-{region}-{account_id}Star Schema: dim_supplier (ALL), dim_product (ALL), dim_location (ALL), dim_date (ALL, 2020–2032, Indian FY)
fact_shipments (DISTKEY supplier_sk, SORTKEY ship_date_sk)
fact_inventory_daily (DISTKEY product_sk)
Spectrum: spectrum_curated + spectrum_mart (external Glue Catalog)
Loaded via: Lambda redshift_loader (Data API COPY PARQUET)
inventory_live: PK=warehouse_id, SK=product_id, GSI=low_stock_flag+updated_at, TTL=30d
operational_alerts: PK=alert_id (ULID), SK=created_at, types: STOCKOUT|DELAY|TEMP_BREACH|SLA_MISS, TTL=7d
pipeline_lineage: PK=pipeline_run_id, SK=step_name, tracks records_in/out/quarantined, duration_ms, status
5 crawlers: raw, staging, curated, mart, dq-results (on-demand schedule)
update_behavior = UPDATE_IN_DATABASE · delete_behavior = LOG
Lake Formation: IAM passthrough mode (IAM_ALLOWED_PRINCIPALS ALL on all 5 DBs)
Athena Workgroup: scip-dev-workgroup → s3://.../athena-results/
Redshift VPC connection
Cognito auth (analysts/operators/admins groups)
Redshift Spectrum serves /mart/ directly for ad-hoc
Lambda: quicksight_refresher (triggered by Step Functions)
Endpoint: ml.t3.medium scip-demand-forecast
API Gateway → Lambda api_router → SageMaker invoke
Model Monitor: weekly drift detection → SNS ml-alerts
3 Feature Groups (online + offline): supplier_reliability, product_demand, inventory_risk
4 action groups: get_supplier_scorecard, check_inventory_status, get_demand_forecast, get_active_alerts
Knowledge Base: S3 /knowledge-base/ → Titan Embeddings v2 (1024-dim) → pgvector (RDS PostgreSQL db.t3.micro)
Docs: procurement_sop_v3, supplier_sla_template, cold_chain_policy, disruption_playbook
API: POST /ask → api_router Lambda → Bedrock Agent invoke
GET /inventory → inventory_live
GET /alerts → operational_alerts
GET /suppliers → Athena (Spectrum)
Cognito authorizer (Phase 5+)
WAF excluded (cost saving)
Lambda: api_router handles all routes
AWS Services Summary
Full-load-and-cdc from MySQL scip_erp to S3. GZIP CSV. 32KB/60s flush intervals.
Auto-scales 0→200 shards. 24h retention. SSE-KMS. Enhanced Fan-Out for Flink.
JQ dynamic partitioning by event_type. 5 min/64 MB buffer. GZIP. Delivers to S3 /raw/events/.
15 PySpark jobs (G.1X × 2 workers). 5 crawlers. Schema Registry (BACKWARD_TRANSITIVE Avro).
14+ states. Parallel branches for staging/curated/mart. Crawler poll loop. Catch ALL → SNS.
Star schema. Spectrum external tables from Glue Catalog. Auto-pause 30 min. Data API COPY PARQUET.
XGBoost quantile regression. Feature Store (3 groups). ml.t3.medium endpoint. Weekly model monitor.
Claude Sonnet 4.6. RAG over S3 knowledge base. 4 action groups. pgvector (RDS PostgreSQL).
Python 3.12 · 256 MB. Covers event ingestion, file validation, KDS consumption, API routing, Redshift loading, feature engineering.
4 tables: shipments_live, inventory_live, operational_alerts, pipeline_lineage. All with GSIs + TTL.
8 routes. 50 burst/100 RPS throttle. Cognito authorizer (Phase 5+). Routes to Lambda for all ops.
SCIP/ custom namespace. 10 metric types. 8 alarms → 4 SNS topics. SCIP-Pipeline-Health dashboard.
Data Flow
Hybrid architecture: 60% batch (CDC from MySQL ERP + nightly ETL) · 40% streaming (IoT/WMS/TMS events). Pipeline run every 4 hours via EventBridge.
End-to-End Data Flow
kds_consumer batch=100 · bisect-on-error · DLQ→SQS
Firehose JQ partition · 5min/64MB · GZIP
shipments_live
inventory_live conditional upsert · low_stock_flag
{event_type}/YYYY/MM/DD/ GZIP · dynamic partition
otd-metrics StatusWindowAggregator count
128 RPU auto-pause · Spectrum
S3 /mart/ + /curated/ via Spectrum
DynamoDB live tables · <1s latency
Lambda api_router · API Gateway
p10 / p50 / p90 demand
GET /forecast · ml.t3.medium
S3 /knowledge-base/ → pgvector
POST /ask · 4 action groups
Correlation ID Strategy
S3 Data Zone Contracts
| Zone | Format | Partitioning | Lifecycle | Purpose |
|---|---|---|---|---|
/raw/ | Parquet+Snappy (events) / CSV+GZIP (DMS) | yr/mo/day/hr | 90d → IA → 180d → GLACIER | Immutable source of truth |
/staging/ | Parquet+Snappy | run_date=YYYY-MM-DD | 30d → IA → expire 60d | Deduped, type-cast, validated |
/curated/ | Parquet+ZSTD | entity/region/yr/mo | 90d → IA → 365d → GLACIER | SCD Type 2, business-ready |
/mart/ | Parquet+ZSTD | metric/yr/mo | 180d → IA, never expire | Aggregated KPIs, BI-ready |
/incoming/ | CSV / JSON | raw | expire 30d | File drop landing zone |
/quarantine/ | Parquet+Snappy | date/source/run_id | expire 30d | DQ failures, review & replay |
/dq-results/ | JSON | date/run_id | 30d → IA → expire 90d | DQ check reports |
/knowledge-base/ | PDF, DOCX, TXT | doc_type | No lifecycle | Bedrock RAG source documents |
/audit-logs/ | JSON (CloudTrail) | AWSLogs/... | 90d → IA → 365d → GLACIER_IR | CloudTrail compliance logs |
Event Schemas
Ingestion Layer
DMS — MySQL CDC to S3
Kinesis Data Streams + Firehose
Lambda Functions — Ingestion
| Function | Trigger | Runtime | Key Logic |
|---|---|---|---|
event_ingest | API Gateway POST /events | Python 3.12 · 256 MB | Validates Avro schema via Glue Schema Registry. Routes to KDS (or S3 direct if DESTINATION_TYPE=S3). Logs lineage to DynamoDB. |
batch_file_validator | S3 ObjectCreated on /incoming/ | Python 3.12 · 256 MB | Schema validation (completeness, non-negative, enum containment). Promotes to /raw/ or quarantines. Sends SNS dq-alerts on failure. |
kds_event_consumer | KDS trigger batch=100 | Python 3.12 · 256 MB | shipment_update → DynamoDB shipments_live (conditional upsert). inventory_change → inventory_live (qty update). sensor_reading → SNS ops-alerts if is_breach=True. |
lineage_writer | Step Functions (START/COMPLETE/FAIL) | Python 3.12 · 256 MB | Writes pipeline_lineage rows: pipeline_run_id, step_name, records_in/out/quarantined, duration_ms, status. |
failure_handler | SQS DLQ / Step Functions Catch | Python 3.12 · 256 MB | Updates lineage to FAILED. Sends SNS pipeline-alerts. Writes error details to DynamoDB. |
alert_router | SNS subscriptions (ops-alerts, dq-alerts) | Python 3.12 · 256 MB | Routes alerts from SNS → DynamoDB operational_alerts. Writes alert_id (ULID), severity, alert_type, resolved_flag. |
Glue Schema Registry
Data Generators (Local Dev)
Python CLI tool to populate the pipeline with synthetic food supply chain data for testing.
| Generator | Command | Output | Destination |
|---|---|---|---|
static_generator.py | run_generators.py static | suppliers.csv (50), products.json (200), inventory_snapshot.csv | S3 /incoming/ |
s3_uploader.py | run_generators.py upload | Uploads static files to S3 /incoming/ | S3 bucket |
kinesis_streamer.py | run_generators.py stream | shipment_update (20/min), inventory_change (10/min), sensor_reading (5/min) | Kinesis Data Streams |
rds_seeder.py | run_generators.py seed-rds | ~50 suppliers, ~200 products, ~2700 orders, ~13500 order lines | RDS MySQL scip_erp |
| All | run_generators.py all | Runs all generators in sequence | All destinations |
SQS Dead Letter Queues
Processing Layer
Step Functions State Machine
Extract run_date + pipeline_run_id
DynamoDB RUNNING row
Promote or quarantine
Fail if pass_rate < 95%
orders, inventory, suppliers,
products, shipments, order_lines
→ S3 /staging/
orders, inventory, suppliers, products
SCD Type 2
→ S3 /curated/
(needs suppliers/current/)
→ S3 /curated/shipments/
delivery_performance,
inventory_health,
supplier_scorecard,
demand_forecast_prep
+ mart crawlers
→ Choice poll loop
Data API COPY PARQUET
→ fact tables
→ RecordComplete
→ NotifySuccess (SNS)
Glue ETL Jobs — All 15
Staging Layer (6 jobs) — Dedup + Type Cast
| Job | Source | Key Transforms | Output |
|---|---|---|---|
suppliers_to_staging | DMS CSV (full-load + CDC) | Dedup by updated_at. Quarantine invalid tier values. Add MD5 hash_key of mutable columns. | Parquet+Snappy, partition run_date |
orders_to_staging | DMS CSV | Dedup by updated_at. Derive lead_time fields (order_date → promised_date). | Parquet+Snappy, partition run_date |
order_lines_to_staging | DMS CSV (CDC) | Dedup by dms_timestamp (CDC strictly increasing). Derive fill_rate, rejection_rate. | Parquet+Snappy, partition run_date |
products_to_staging | DMS CSV | Dedup by created_at. Filter invalid categories. Add hash_key. .cache() before double count(). | Parquet+Snappy, partition run_date |
shipments_to_staging | Kinesis Firehose NDJSON (S3) | Dedup on (shipment_id, status) by event_ts. Add is_on_time (event_ts ≤ estimated_delivery). | Parquet+Snappy, partition run_date |
inventory_to_staging | WMS batch CSV | Cast types. Add stock_value_inr (qty × unit_cost). Add low_stock_flag, stockout_flag. | Parquet+Snappy, partition run_date |
DQ Layer (1 job)
| Check | Threshold | Action on Fail |
|---|---|---|
| completeness(primary_key) ≥ 1.0 | Strict | Quarantine entire batch |
| isUnique(primary_key) ≥ 0.99 | 99% | Deduplicate; flag duplicates |
| schema_matches(registry_schema) | Strict | Quarantine + SNS alert |
| freshness(event_time) ≤ 6 hours | Advisory | SNS warning only |
| referentialIntegrity(supplier_id) | 99% | Quarantine orphan records |
| isNonNegative(quantity) | Strict | Quarantine + flag |
| isContainedIn(status, ENUM) | Strict | Quarantine |
| meanInRange(temperature, -20, 5) | Advisory | SNS cold chain warning |
Publishes dq_pass_rate_pct, dq_quarantined_record_count, dq_check_duration_ms to SCIP/DQ CloudWatch namespace. Pipeline fails (Step Functions Fail state) if any dataset pass_rate < 95%.
Curated Layer (5 jobs) — SCD Type 2
| Job | Key Transforms |
|---|---|
suppliers_to_curated | Full SCD Type 2: expire changed rows (eff_end_date=today, is_current=False), insert new versions. Output: active/ snapshot + history/ archive + redshift/ (Redshift-formatted subset). |
orders_to_curated | Enrich with supplier dimension join. Add delivery_status_bucket (EARLY/ON_TIME/LATE), is_on_time boolean. |
products_to_curated | Add category_path (l1 / l2 / l3), margin_band (HIGH/MED/LOW), temperature_class (AMBIENT/CHILLED/FROZEN). Write products/ (full) + products_dim/ (14-col Redshift subset). |
shipments_to_curated | Add carrier_reliability_score (static map by carrier name), delivery_outcome (DELIVERED/EXCEPTION/RETURNED). |
inventory_to_curated | Add avg_daily_consumption (lag window: prev_qty - qty_on_hand, clamped ≥ 0), days_of_supply (qty / avg_consumption), stockout_risk flag. |
Mart Layer (4 jobs) — Aggregations
| Job | Group By | Key Output Metrics |
|---|---|---|
delivery_performance | (supplier_id, warehouse_id, carrier_name) | total_shipments, on_time_count, otd_pct, exception_count, avg_delay_days |
inventory_health | (warehouse_id, category_l1, temperature_class) | stockout_count, low_stock_count, total_stock_value_inr, avg_days_of_supply |
supplier_scorecard | supplier_id | Composite 0–100 score: OTD 40% + fill_rate 30% + quality 20% + lead_time 10%. sla_breach_flag when score < 70. |
demand_forecast_prep | Join curated inventory + products | Calendar features (day_of_week, is_weekend, fiscal_month) + SageMaker-ready feature set. |
KDA Managed Flink (PyFlink)
Lambda Functions — Processing & Serving
| Function | Trigger | Key Logic |
|---|---|---|
redshift_loader | Step Functions LoadRedshift state | Executes Redshift Data API COPY FORMAT AS PARQUET from S3 /mart/ into fact_shipments and fact_inventory_daily. |
quicksight_refresher | Step Functions RefreshQuickSight state | Triggers QuickSight SPICE dataset refresh for all 5 dashboards. |
schema_init | Terraform aws_lambda_invocation (Phase 5 deploy) | Runs all Redshift DDL: dimensions, facts, Spectrum schemas, dim_date seed (2020–2032). Triggers on code SHA-256 change. |
feature_engineer | EventBridge / manual trigger | Reads S3 /curated/ → computes supplier_reliability, product_demand, inventory_risk feature vectors → writes to SageMaker Feature Store (online + offline). |
api_router | API Gateway (GET /shipments, /inventory, /alerts, /suppliers, POST /ask, /forecast) | Routes to DynamoDB (live ops), Athena Spectrum (analytics), SageMaker endpoint (forecasts), or Bedrock Agent (NL queries). |
agent_actions | Bedrock Agent action group | 4 action groups: get_supplier_scorecard (DynamoDB/Redshift), check_inventory_status (DynamoDB), get_demand_forecast (SageMaker endpoint), get_active_alerts (DynamoDB). |
pgvector_init | Terraform invoke (Phase 7) | Creates pgvector schema in RDS PostgreSQL, creates embeddings table (1024-dim), initializes Bedrock KB connection. |
rds_seeder | Manual invoke | Seeds scip_erp MySQL: action=seed inserts ~50 suppliers, ~200 products, ~2700 orders, ~13500 order_lines. action=query validates. |
Storage & Data Warehouse
Redshift Serverless — Star Schema
Dimension Tables
| Table | DISTSTYLE | SORTKEY | Key Columns |
|---|---|---|---|
dim_supplier | ALL | eff_start_date | supplier_sk (IDENTITY), supplier_id, name, tier (TIER1/2/3), city, state, country, lead_time_days, quality_score, is_active, eff_start_date, eff_end_date (default 9999-12-31), is_current, hash_key (MD5), pipeline_run_id |
dim_product | ALL | product_id | product_sk (IDENTITY), product_id, sku, name, category_l1/l2/l3, unit_cost_inr, shelf_life_days, requires_cold_chain, cold_chain_min_c, cold_chain_max_c, is_active, pipeline_run_id |
dim_location | ALL | location_id | location_sk (IDENTITY), location_id, location_type, name, city, state, region, lat, lng (DECIMAL 9,6), timezone |
dim_date | ALL | date_sk | date_sk (INTEGER PK), full_date, year, quarter, month, month_name, week_of_year, day_of_month, day_of_week, day_name, is_weekend, is_holiday_india, fiscal_year, fiscal_quarter, fiscal_month. Seeded 2020–2032+. Indian fiscal year starts April. |
Fact Tables
| Table | DISTKEY | SORTKEY | Key Columns |
|---|---|---|---|
fact_shipments | supplier_sk | ship_date_sk | shipment_sk (IDENTITY), shipment_id, supplier_sk, product_sk, origin_loc_sk, dest_loc_sk, ship_date_sk, promised_date_sk, actual_delivery_date_sk (all FK to dim_date), carrier_name, shipment_qty, shipment_weight_kg, delay_days (negative=early), is_on_time, temperature_breach, order_id, pipeline_run_id, run_date |
fact_inventory_daily | product_sk | snapshot_date_sk | snapshot_sk (IDENTITY), warehouse_sk (FK dim_location), product_sk, snapshot_date_sk (FK dim_date), qty_on_hand, qty_reserved, qty_available, reorder_point, safety_stock, days_of_supply, low_stock_flag, pipeline_run_id, run_date |
DynamoDB — 4 Operational Tables
Glue Data Catalog
| Database | Tables | Format | Crawler |
|---|---|---|---|
scip-dev_raw | DMS CSVs, Firehose NDJSON events | CSV+GZIP / NDJSON | raw-crawler (on-demand) |
scip-dev_staging | suppliers, orders, order_lines, products, shipments, inventory | Parquet+Snappy, partition run_date | staging-crawler (on-demand) |
scip-dev_curated | suppliers (active+history+redshift), orders, products, shipments, inventory | Parquet+ZSTD | curated-crawler (Step Functions) |
scip-dev_mart | delivery_performance, inventory_health, supplier_scorecard, demand_forecast_prep | Parquet+ZSTD | mart-crawler (Step Functions) |
scip-dev_dq | DQ check reports | JSON | dq-results-crawler (on-demand) |
Lake Formation
lf-test-allowed and lf-test-denied validate access control. Actual column-level security and row-level filters disabled in dev to reduce complexity.SNS Topics & Alerting
Triggered by: Step Functions failure, Glue job failure, Cost >$15/day. Subscriber: ops team email/PagerDuty.
Triggered by: DQ pass_rate <95%, quarantine events, schema mismatch. Subscriber: data quality team.
Triggered by: stream lag >120s, API 5xx >1%, sensor breach, silent source (0 records 30min).
Triggered by: SageMaker Model Monitor drift score >0.3. Subscriber: ML team.
ML & AI Layer
SageMaker demand forecasting + Bedrock RAG-based supply chain copilot powered by Claude Sonnet 4.6.
SageMaker Pipeline — Demand Forecast
SKAgentProcessor
Calendar + lag features
Targets: p10, p50, p90
30-day demand horizon
Fail pipeline if
RMSE > threshold
in Model Registry
Champion/challenger
Endpoint: scip-demand-forecast
Real-time p10/p50/p90
SageMaker Feature Store
| Feature Group | Features | Store Type | Source |
|---|---|---|---|
supplier_reliability | historical_otd_pct, avg_lead_time_days, quality_score_rolling_30d, sla_breach_count_90d | Online + Offline | Lambda: feature_engineer reads /curated/suppliers/ + /mart/supplier_scorecard/ |
product_demand | avg_daily_units_30d, demand_volatility (std/mean), stockout_frequency_30d, day_of_week_seasonal_index | Online + Offline | Lambda: feature_engineer reads /curated/inventory/ + /mart/inventory_health/ |
inventory_risk | current_days_of_supply, avg_daily_consumption, stockout_risk_flag, reorder_point_coverage_ratio | Online + Offline | Lambda: feature_engineer reads /curated/inventory/ |
SageMaker Model Monitor
Bedrock Knowledge Base — RAG
Bedrock Agent — Supply Chain Copilot
Example NL Queries → Agent Responses
| User Query | Agent Action | Data Source |
|---|---|---|
| "What is the SOP for a cold chain breach in the dairy category?" | RAG over knowledge base | cold_chain_policy_2026.txt + category_dairy_sourcing.txt via pgvector |
| "Is Supplier SUP-012 meeting its SLA?" | get_supplier_scorecard(SUP-012) | DynamoDB / Redshift mart supplier_scorecard |
| "What's the demand forecast for SKU PRD-045 in Mumbai next 30 days?" | get_demand_forecast(PRD-045, Mumbai) | SageMaker scip-demand-forecast endpoint |
| "Are there any critical stockout alerts right now?" | get_active_alerts(severity=CRITICAL) | DynamoDB operational_alerts GSI scan |
Infrastructure — Terraform
8-phase Terraform deployment. Providers: AWS ~5.60, random ~3.6. Local state backend (dev). Region: ap-south-1. Project: scip. Environment: dev.
Deployment Phases
VPC: 10.0.0.0/16, 2 private subnets (10.0.1.0/24, 10.0.2.0/24), 2 AZs (ap-south-1a/b). Security groups: rds-sg, dms-sg, seeder-lambda-sg. VPC Endpoints: S3 Gateway (free) + Interface: Glue, KMS, Secrets Manager, SNS, SQS, DynamoDB.
IAM: 9 roles — glue, lambda-stream, lambda-api, dms, redshift (trust: redshift + redshift-serverless + quicksight), sagemaker, bedrock, stepfunctions, eventbridge.
S3: 9 buckets via shared module, lifecycle rules, DenyNonHTTPS. DynamoDB: 4 tables + GSIs + TTL. Catalog: 5 Glue DBs + Schema Registry (3 Avro schemas). CloudWatch: log groups, 10 custom metrics, 8 alarms, SCIP-Pipeline-Health dashboard.
API Gateway HTTP v2 (8 routes, 50 burst/100 RPS). 6 Lambda functions deployed. DESTINATION_TYPE=S3 (no KDS cost yet). S3 event notifications → batch_file_validator. SQS kds-consumer-dlq → failure_handler.
KDS ON_DEMAND stream (24h retention, SSE-KMS). Firehose (JQ dynamic partitioning). KDA Managed Flink (deploy_flink=false toggle, ~$79/mo if enabled). kds_event_consumer Lambda (batch=100, bisect-on-error). Switch DESTINATION_TYPE=KDS in event_ingest Lambda.
RDS MySQL 8.0 (db.t3.micro, 20GB). DMS (dms.t3.small, full-load-and-cdc). 15 Glue job definitions (Glue 4.0, G.1X × 2 workers, scripts on S3 raw/glue-scripts/). 5 crawlers (on-demand schedule). rds_seeder Lambda (VPC-attached). Scripts uploaded from /glue_jobs/ directory.
Step Functions Standard workflow (ASL from step_functions/scip_etl_main.asl.json — template substitutes bucket names and ARNs). EventBridge cron every 4h with pipeline_run_id input transformer. Stub Lambdas for redshift_loader + quicksight_refresher (replaced in Phase 5).
Redshift Serverless namespace + workgroup (128 RPU base, auto-pause 30 min). schema_init Lambda invoked on first deploy (all Redshift DDL + dim_date seed 2020–2032). Cognito user pool + groups (analysts/operators/admins). QuickSight VPC connection + Redshift data source. API Gateway Cognito authorizer activated.
3 SageMaker Feature Groups. 5-step pipeline (Process→Train→Evaluate→Register→Deploy). ml.t3.medium real-time endpoint. Weekly Model Monitor (baseline recompute, drift → SNS ml-alerts). SageMaker execution IAM role.
RDS PostgreSQL db.t3.micro (pgvector). Bedrock Knowledge Base (S3 → Titan Embeddings v2 → pgvector). Bedrock Agent (4 action groups, Claude Sonnet 4.6). pgvector_init Lambda invoked to create schema + embeddings table.
CloudTrail: management events + all S3 data events on scip-* buckets, 1-year retention. 7 AWS Config rules (s3-bucket-public-read-prohibited, iam-password-policy, vpc-flow-logs-enabled, lambda-inside-vpc, lambda-dlq-check, s3-bucket-ssl-requests-only, cloudtrail-enabled). Lake Formation: IAM passthrough, database grants, Glue + Redshift wildcard table grants. KMS CMKs / WAF / Macie excluded (cost saving).
IAM Roles — Least Privilege
| Role | Trust Principal | Key Permissions |
|---|---|---|
scip-dev-glue-role | glue.amazonaws.com | S3 read/write (raw/staging/curated/mart), Glue Catalog CRUD, CloudWatch logs, Secrets Manager GetSecretValue, Redshift Data API |
scip-dev-lambda-stream-role | lambda.amazonaws.com | KDS GetRecords/PutRecord, DynamoDB CRUD (all 4 tables), SNS Publish (all 4 topics), SQS SendMessage, Glue GetRegistry/GetSchema, Redshift Data API, iam:PassRole |
scip-dev-lambda-api-role | lambda.amazonaws.com | DynamoDB Read (shipments_live/inventory_live/alerts), Athena StartQueryExecution, SageMaker InvokeEndpoint, Bedrock InvokeAgent, QuickSight CreateIngestion |
scip-dev-dms-role | dms.amazonaws.com | S3 PutObject on /raw/dms/ prefix, Secrets Manager GetSecretValue (MySQL credentials) |
scip-dev-redshift-role | redshift.amazonaws.com + redshift-serverless.amazonaws.com + quicksight.amazonaws.com | S3 GetObject on /mart/ and /curated/ (Spectrum COPY), Glue GetDatabase/GetTable (Spectrum catalog), CloudWatch PutMetricData |
scip-dev-sagemaker-role | sagemaker.amazonaws.com | S3 read/write (/curated/, /mart/, sagemaker-artifacts/), Feature Store PutRecord/GetRecord, ECR GetDownloadUrlForLayer, CloudWatch PutMetricData |
scip-dev-bedrock-role | bedrock.amazonaws.com | S3 GetObject on /knowledge-base/, RDS Data API (pgvector PostgreSQL), Bedrock InvokeModel (Claude Sonnet 4.6), Lambda InvokeFunction (agent_actions) |
scip-dev-stepfunctions-role | states.amazonaws.com | Lambda InvokeFunction, Glue StartJobRun, Glue GetJobRun, Glue StartCrawler, Glue GetCrawler, SNS Publish, CloudWatch PutMetricData |
scip-dev-eventbridge-role | scheduler.amazonaws.com | states:StartExecution on scip-etl-main Step Functions ARN only |
Cost Estimate (Dev — Continuous)
Terraform Modules
Reusable S3 bucket with encryption (SSE-S3), versioning, public-access-block, DenyNonHTTPS bucket policy, and configurable lifecycle rules. Used by all 9 buckets in Phase 0.
Reusable IAM role with configurable trust policy and inline policies. All 9 roles in Phase 0 use this module to enforce consistent tagging and naming.
Governance & Operations
Data Quality Framework
| Check Type | Rule | Threshold | Action | CW Metric |
|---|---|---|---|---|
| Completeness | primary_key NOT NULL | 100% strict | Quarantine entire batch → SNS dq-alerts | dq_pass_rate_pct |
| Uniqueness | isUnique(primary_key) | ≥ 99% | Deduplicate; flag duplicates in /quarantine/ | dq_quarantined_record_count |
| Schema match | schema_matches(Glue Registry Avro) | Strict | Quarantine + SNS alert (schema evolution violation) | dq_check_duration_ms |
| Freshness | event_time within 6 hours | Advisory | SNS ops-alerts warning only (stale data, don't block) | — |
| Referential integrity | supplier_id exists in dim_supplier | ≥ 99% | Quarantine orphan records → SNS dq-alerts | — |
| Non-negative | qty_on_hand, shipment_qty ≥ 0 | Strict | Quarantine + flag in /quarantine/ metadata | — |
| Enum containment | status IN (CREATED, PICKED, IN_TRANSIT, DELIVERED, EXCEPTION, RETURNED) | Strict | Quarantine | — |
| Temperature range | temperature_c mean IN [-20, 5] (cold chain) | Advisory | SNS cold chain warning (sensor breach escalation) | — |
CloudWatch Alarms
| Alarm | Metric | Threshold | SNS Topic |
|---|---|---|---|
| DQ Failure Rate | SCIP/DQ/dq_pass_rate_pct | < 95% | scip-dq-alerts |
| Stream Consumer Lag | SCIP/Stream/IteratorAgeMilliseconds | > 120,000 ms | scip-ops-alerts |
| Glue Job Failure | Glue/JobRunFailed | ≥ 1 occurrence | scip-pipeline-alerts |
| Step Functions Failure | States/ExecutionsFailed | ≥ 1 occurrence | scip-pipeline-alerts |
| API 5xx Errors | SCIP/API/5xxErrorRatePct | > 1% for 5 min | scip-ops-alerts |
| ML Data Drift | SCIP/ML/DriftScore | > 0.3 | scip-ml-alerts |
| Silent Stream Source | KinesisDataStreams/IncomingRecords | == 0 for 30 min | scip-ops-alerts |
| Daily Cost Burn | SCIP/Cost/DailySpendUSD | > $15/day | scip-pipeline-alerts |
Security Controls
AWS Config Rules (Phase 8)
All 9 S3 buckets must have public access blocked. Auto-remediation alert.
Enforces minimum password length, complexity, rotation for IAM users.
VPC flow logs must be enabled for network traffic audit.
All Lambda functions (seeder, kds_consumer) that need RDS access must be VPC-attached.
All event-triggered Lambda functions must have a DLQ configured.
All S3 bucket policies must deny non-HTTPS requests (enforced by DenyNonHTTPS policy).
CloudTrail must be enabled with multi-region tracking and S3 data events on scip-* buckets.
CloudTrail Audit
Operational SOPs
| SOP Document | Covers | Location |
|---|---|---|
SOP_FIRST_TIME_SETUP.md | Initial AWS account setup, Terraform init, Phase 0–8 deploy sequence, pre-flight checklist | docs/ |
SOP_DAILY_PIPELINE.md | Daily health check, EventBridge schedule verification, DQ alert triage, Redshift auto-pause checks | docs/ |
SOP_DEPLOYMENT.md | Terraform plan/apply workflow, blue/green considerations, Glue script upload procedure, Lambda deployment | docs/ |
SOP_INCIDENT_RESPONSE.md | Pipeline failure triage, DQ quarantine replay, Kinesis stream lag remediation, Step Functions rerun procedure | docs/ |
DEPLOYMENT_GUIDE.md | End-to-end deployment from scratch with exact bash commands, 7-day build guide | docs/ |
Key Architecture Decisions
DEA-C01 Exam Domain Coverage
| Domain | SCIP Components | Coverage |
|---|---|---|
| Data Ingestion & Transformation | DMS (CDC), Kinesis (streaming), Glue ETL (15 jobs), Lambda (validation), Firehose (buffering) | ✓ Full |
| Data Store Management | S3 (9 buckets, lifecycle), Redshift Serverless (star schema, Spectrum), DynamoDB (4 tables, GSIs, TTL), Glue Catalog | ✓ Full |
| Data Operations & Support | Step Functions (orchestration), EventBridge (scheduling), CloudWatch (alarms, dashboards), SQS DLQs, SNS (4 topics) | ✓ Full |
| Data Security & Governance | IAM (9 roles), Lake Formation, Cognito, CloudTrail, AWS Config (7 rules), Secrets Manager, VPC endpoints | ✓ Full |
| Data Analysis & Visualization | Athena (Spectrum queries), QuickSight (5 dashboards, SPICE), Redshift (star schema queries) | ✓ Full |
| ML & AI on AWS | SageMaker (pipeline, feature store, endpoint, model monitor), Bedrock (KB, Agent), Claude Sonnet 4.6 | ✓ Full |