Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Enterprise E-Commerce Architecture Blueprint

Complete Architecture Overview

This Enterprise E-Commerce Architecture Blueprint is a scalable, secure, and resilient cloud-native design for a global online retail platform, built on AWS. It integrates microservices for Auth, Catalog, Order, Payment, Inventory, and Analytics, orchestrated by an event-driven core using EventBridge, SQS, and Step Functions. Client applications (web, iOS, Android) access the platform via CloudFront with WAF protection and API Gateway for secure endpoints. Data is managed with Aurora Global Database, DynamoDB Global Tables, ElastiCache for caching, and OpenSearch for search, ensuring low-latency and global consistency. Security is enforced through Cognito, KMS, QLDB, and PCI-compliant infrastructure. The architecture is detailed across six diagrams, each focusing on a critical layer: Client, API Gateway, Catalog Service, Order Processing, and Payment Processing, providing a modular and observable system for millions of users.

The architecture is split into layered diagrams for clarity, ensuring a comprehensive view of a globally scalable e-commerce platform.
graph TD %% Main Components classDef client fill:#9e9e9e,stroke:#333; classDef infra fill:#607d8b,stroke:#333; classDef service fill:#2196f3,stroke:#333; classDef data fill:#4caf50,stroke:#333; classDef event fill:#9c27b0,stroke:#333; Client["Client Apps (Web/iOS/Android)"]:::client CDN["CloudFront + WAF"]:::infra API["API Gateway"]:::infra Auth["Auth Service"]:::service Catalog["Catalog Service"]:::service Order["Order Service"]:::service Payment["Payment Service"]:::service EventBus["EventBridge"]:::event DB["Aurora + DynamoDB"]:::data Cache["ElastiCache"]:::data Client --> CDN --> API API --> Auth API --> Catalog --> DB & Cache API --> Order --> EventBus EventBus --> Payment & Inventory Payment -->|Saga| Order Order --> DB EventBus --> Analytics["Analytics Service"]
This overview diagram illustrates the high-level flow from client access to service interactions and data persistence.

Architecture Principles

1. Layered Isolation

  • Presentation: CloudFront, Web Apps
  • Edge: WAF, Route53
  • API: Gateway + Lambda Auth
  • Services: ECS/EKS microservices
  • Data: Multi-model persistence

2. Event-Driven Core

  • EventBridge for state changes
  • SQS for async processing
  • Step Functions for workflows
  • Dead-letter queues for resilience

3. Global Data

  • Aurora Global Database
  • DynamoDB Global Tables
  • ElastiCache Multi-AZ
  • S3 Cross-Region Replication

Key Performance Metrics

Component Target SLA Latency Throughput
API Gateway 99.95% <50ms 10,000 RPS
Catalog Service 99.99% <100ms (cache) 5,000 RPS
Order Processing 99.9% 500ms (sync) 1,000 TPS
Payment Service 99.95% 1s (3DSecure) 500 TPS

1. Client Architecture

This diagram illustrates the client-side architecture, where Web App (React), iOS (SwiftUI), and Android (Kotlin) applications interact with the platform via CloudFront and API Gateway. CloudFront serves as a global CDN, caching static assets in S3 and executing edge logic with Lambda@Edge for tasks like request normalization. Web apps leverage CloudFront for low-latency delivery, while mobile apps connect directly to API Gateway for dynamic APIs. The client architecture connects to the API Gateway Architecture (Diagram 2) for secure backend interactions. Key features include performance optimization through caching and code splitting, and security via CSP headers and JWT tokens.

graph LR %% Client Architecture classDef web fill:#4285f4,stroke:#333; classDef mobile fill:#34a853,stroke:#333; classDef cdn fill:#ff6d01,stroke:#333; Web["Web App (React)"]:::web iOS["iOS (SwiftUI)"]:::mobile Android["Android (Kotlin)"]:::mobile CDN["CloudFront"]:::cdn API["API Gateway"] Web --> CDN --> API iOS --> API Android --> API CDN --> S3["S3 (Web Assets)"] CDN --> LambdaEdge["Lambda@Edge"]
The Client Architecture ensures low-latency and secure access for web and mobile users.

Key Features

Performance Optimization

  • Static assets via CloudFront (TTL 1yr)
  • Dynamic content with stale-while-revalidate
  • Code splitting with Webpack
  • Progressive Web App capabilities

Security

  • CSP headers for XSS protection
  • JWT in HttpOnly cookies
  • Certificate pinning (mobile)
  • Obfuscated API keys
// Sample React API Client with Retry
const apiClient = axios.create({
  baseURL: process.env.API_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

apiClient.interceptors.response.use(null, (error) => {
  if (error.config && error.response && error.response.status >= 500) {
    return new Promise((resolve) => {
      setTimeout(() => resolve(apiClient(error.config)), 1000);
    });
  }
  return Promise.reject(error);
});

export const getProduct = (id) => 
  apiClient.get(`/products/${id}`, {
    headers: {
      'Cache-Control': 'max-age=60, stale-while-revalidate=3600'
    }
  });

2. API Gateway Architecture

This diagram details the API Gateway layer, which serves as the secure entry point for client requests from the Client Architecture (Diagram 1). It integrates with a Lambda Authorizer for JWT validation using Cognito User Pool and KMS for secure key management. The gateway routes requests to microservices like Catalog, Order, and Payment (Diagrams 3, 4, and 5) and is protected by WAF rules to block malicious traffic, such as SQL injection and XSS attacks. Throttling and caching configurations ensure scalability and performance, with endpoints like /products supporting optional authentication and /orders requiring MFA.

graph TB %% API Gateway Flow classDef gateway fill:#ff9800,stroke:#333; classDef auth fill:#673ab7,stroke:#333; classDef service fill:#2196f3,stroke:#333; Client --> APIGW["API Gateway"]:::gateway APIGW --> Authorizer["Lambda Authorizer"]:::auth Authorizer --> Cognito["Cognito User Pool"] Authorizer --> KMS["KMS JWT Validation"] APIGW -->|/products| CatalogService:::service APIGW -->|/orders| OrderService:::service APIGW -->|/payments| PaymentService:::service APIGW --> WAF["AWS WAF Rules"] WAF -->|Block| BadActors["SQLi/XSS/Bad Bots"]
The API Gateway Architecture provides secure and scalable API management with robust authentication.

Gateway Configuration

Endpoint Throttling Cache TTL Auth
/products 1000 RPS 60s Optional
/cart 500 RPS 0s Required
/orders 200 RPS 0s Required + MFA
# Terraform for API Gateway
resource "aws_api_gateway_rest_api" "ecommerce" {
  name        = "ecommerce-api"
  description = "Main API Gateway for E-Commerce Platform"

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

resource "aws_api_gateway_authorizer" "jwt" {
  name          = "jwt-authorizer"
  rest_api_id   = aws_api_gateway_rest_api.ecommerce.id
  authorizer_uri = aws_lambda_function.authorizer.invoke_arn
  type          = "TOKEN"
  identity_source = "method.request.header.Authorization"
}

resource "aws_wafv2_web_acl_association" "api" {
  resource_arn = aws_api_gateway_stage.prod.arn
  web_acl_arn  = aws_wafv2_web_acl.api.arn
}

3. Catalog Service Deep Dive

This diagram focuses on the Catalog Service, which manages product listings and search functionality, receiving requests from the API Gateway (Diagram 2). It interacts with Aurora PostgreSQL for relational data, ElastiCache (Redis) for caching, and OpenSearch for full-text search. The service supports Admin Console for CRUD operations and uses Change Data Capture (CDC) via EventBridge to trigger cache invalidation and search index updates. The Catalog Service connects to the Order Processing System (Diagram 4) for inventory-related events and supports high-traffic reads with a DynamoDB cache. The data model and cache strategy ensure low-latency and consistency.

graph LR %% Catalog Service classDef api fill:#ff9800,stroke:#333; classDef service fill:#2196f3,stroke:#333; classDef db fill:#4caf50,stroke:#333; classDef cache fill:#ff5722,stroke:#333; API --> CatalogService["Catalog Service"]:::service CatalogService --> Cache["ElastiCache (Redis)"]:::cache CatalogService --> DB["Aurora PostgreSQL"]:::db CatalogService --> Search["OpenSearch"]:::db Admin["Admin Console"] -->|CRUD| CatalogService CatalogService -->|CDC| EventBridge["Product Events"] EventBridge -->|Invalidate| Cache EventBridge -->|Index| Search
The Catalog Service ensures fast and scalable product data access with caching and search integration.

Data Model

-- PostgreSQL Schema
CREATE TABLE products (
  id UUID PRIMARY KEY,
  sku VARCHAR(32) UNIQUE,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  price DECIMAL(10,2) CHECK (price >= 0),
  inventory_count INTEGER DEFAULT 0,
  categories JSONB,
  attributes JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ
);

-- DynamoDB Schema (for high-traffic reads)
{
  "TableName": "ProductCache",
  "KeySchema": [
    { "AttributeName": "pk", "KeyType": "HASH" },  // "PROD#123"
    { "AttributeName": "sk", "KeyType": "RANGE" }  // "METADATA"
  ],
  "GlobalSecondaryIndexes": [
    {
      "IndexName": "CategoryIndex",
      "KeySchema": [
        { "AttributeName": "category", "KeyType": "HASH" },
        { "AttributeName": "price", "KeyType": "RANGE" }
      ],
      "Projection": { "ProjectionType": "INCLUDE", "NonKeyAttributes": ["name","image"] }
    }
  ]
}

Cache Strategy

Read-Through Cache

  • Cache hit: 5ms response
  • Cache miss: 50ms (DB + warm cache)
  • TTL: 5 minutes (product data)
  • TTL: 1 hour (category listings)

Invalidation Triggers

  • Price changes
  • Inventory updates
  • Product description edits
  • Scheduled midnight flush

4. Order Processing System

This diagram illustrates the Order Processing System, which handles order creation and fulfillment, receiving requests from the API Gateway (Diagram 2). The Order Service writes to DynamoDB Orders with ACID transactions and emits order.placed events via EventBridge. Step Functions orchestrates a saga pattern, coordinating Inventory, Payment (Diagram 5), and Logistics services. Failures trigger a Compensation Flow to rollback changes, ensuring consistency. The system connects to the Catalog Service (Diagram 3) for inventory checks and supports state transitions from PENDING to DELIVERED or FAILED.

graph TD %% Order Processing classDef service fill:#2196f3,stroke:#333; classDef event fill:#9c27b0,stroke:#333; classDef db fill:#4caf50,stroke:#333; Client -->|Place Order| OrderService:::service OrderService -->|"Create (ACID Transaction)"| DynamoDB["DynamoDB Orders"]:::db OrderService -->|"order.placed"| EventBridge:::event EventBridge -->|Start Saga| StepFunctions["Fulfillment Workflow"] StepFunctions --> Inventory["Reserve Stock"] StepFunctions --> Payment["Process Payment"] StepFunctions --> Logistics["Schedule Delivery"] Payment -->|Failed| Compensate["Compensation Flow"] Compensate --> Inventory Compensate --> OrderService
The Order Processing System ensures reliable order fulfillment with saga-based coordination.

Saga Pattern Implementation

// Order Saga Compensation Handler
exports.handleCompensation = async (event) => {
  const { orderId, failureStep } = event;
  
  // 1. Update Order Status
  await dynamodb.update({
    TableName: 'Orders',
    Key: { id: orderId },
    UpdateExpression: 'SET #status = :status',
    ExpressionAttributeNames: { '#status': 'status' },
    ExpressionAttributeValues: { ':status': 'FAILED' }
  });

  // 2. Execute Compensation Based on Failure Point
  switch(failureStep) {
    case 'PAYMENT_FAILED':
      await inventoryService.releaseStock(orderId);
      break;
      
    case 'INVENTORY_UNAVAILABLE':
      await paymentService.refund(orderId);
      break;
      
    case 'SHIPPING_FAILED':
      await paymentService.refund(orderId);
      await inventoryService.releaseStock(orderId);
      break;
  }
  
  // 3. Notify User
  await sns.publish({
    TopicArn: process.env.NOTIFICATIONS_TOPIC,
    Message: JSON.stringify({
      type: 'ORDER_FAILED',
      orderId,
      reason: failureStep
    })
  });
};

Order State Transitions

stateDiagram-v2 [*] --> PENDING PENDING --> PROCESSING: Payment Received PROCESSING --> FULFILLED: Inventory Reserved PROCESSING --> FAILED: Payment Failed FULFILLED --> SHIPPED: Logistics Confirmed FULFILLED --> CANCELLED: User Cancelled SHIPPED --> DELIVERED: Carrier Update SHIPPED --> RETURNED: Customer Initiated

5. Payment Processing Architecture

This diagram details the Payment Processing Architecture, which secures transactions within a PCI-Compliant VPC. The Payment Service, invoked by the Order Processing System (Diagram 4) via EventBridge, uses a Payment Vault (HSM) for card tokenization and integrates with external Payment Processor APIs. KMS handles encryption, and QLDB maintains an immutable audit ledger. Asynchronous events from processors are processed via SQS. Security controls include PCI-DSS compliance and fraud prevention with 3D Secure and ML scoring, ensuring robust payment handling.

graph LR %% Payment Flow classDef service fill:#2196f3,stroke:#333; classDef secure fill:#f44336,stroke:#333; classDef external fill:#ff9800,stroke:#333; OrderService --> PaymentService:::service PaymentService --> PCI["PCI-Compliant VPC"]:::secure PCI --> Vault["Payment Vault (HSM)"]:::secure PCI --> Processor["Payment Processor API"]:::external PaymentService -->|Tokenize| KMS["KMS (Encryption)"]:::secure PaymentService -->|Audit| QLDB["QLDB (Immutable Ledger)"]:::secure Processor -->|Webhook| SQS["SQS (Async Events)"]:::service SQS --> PaymentService
The Payment Processing Architecture ensures secure and compliant transaction handling.

Security Controls

Data Protection

  • PCI-DSS Level 1 Certified
  • HSM for card tokenization
  • Field-level encryption
  • No PAN storage in logs

Fraud Prevention

  • 3D Secure 2.0
  • Velocity checks
  • IP geolocation
  • Machine learning scoring
# Terraform for PCI-Compliant Resources
resource "aws_vpc" "pci" {
  cidr_block = "10.1.0.0/16"
  enable_dns_hostnames = true
  tags = {
    Name = "PCI-VPC"
    Compliance = "PCI-DSS"
  }
}

resource "aws_cloudhsm_v2_cluster" "payment_hsm" {
  hsm_type   = "hsm1.medium"
  subnet_ids = aws_subnet.pci[*].id
  tags = {
    Purpose = "Card Data Tokenization"
  }
}

resource "aws_kms_key" "payment" {
  description             = "Payment Processing Key"
  deletion_window_in_days = 30
  enable_key_rotation     = true
  policy = data.aws_iam_policy_document.pci_kms.json
  tags = {
    Compliance = "PCI-DSS"
  }
}