Aws patterns

From FerroxLabs/murage · View interactive version

Aws patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level aws architecture patterns implementation: cloud and architecture decision frameworks, production-ready patterns, and concrete templates for aws patterns workflows. Use when the user asks about aws architecture patterns, aws patterns configuration, or cloud best practices for aws

How to use this skill

Skill file

AWS Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Characterize the Workload

Before recommending any pattern, classify the workload along four axes:

Determine the availability tier:

2. Select the Compute Pattern

Apply this decision tree:

Is the workload event-driven with discrete, short-lived invocations (< 15 minutes)?

Is the workload containerized?

Is the workload a traditional three-tier web application?

Compute sizing rules:

3. Select the Data Storage Pattern

Apply the following rules in order:

Relational workload (ACID transactions, complex joins, reporting):

High-throughput key-value or document workload (>10,000 writes/second or single-digit millisecond latency required):

Large object / binary / unstructured storage:

Caching layer:

Time-series and analytical workloads:

4. Design the Messaging and Integration Pattern

Choose based on the required semantics:

Fan-out (one publisher, many consumers):

Work queue (competing consumers, each message processed once):

High-throughput streaming (>1,000 events/second, replay required, multiple independent consumers):

Synchronous API integration:

Orchestration vs. choreography:

5. Design the Network and Security Architecture

VPC structure (three-tier standard):

Security group design:

IAM pattern:

Secrets management:

Encryption standards:

6. Design Observability and Operational Controls

The Three Pillars on AWS:

Metrics -- CloudWatch:

Logs -- CloudWatch Logs / OpenSearch:

Traces -- AWS X-Ray:

Alerting:

7. Define the Deployment and Resilience Strategy

Deployment patterns:

Auto Scaling:

Resilience patterns:

8. Document Architecture Decisions

Create an Architecture Decision Record (ADR) for every non-obvious choice. A minimal ADR contains:

Record ADRs in a /docs/adr/ directory in the application repository, numbered sequentially (ADR-001, ADR-002). Link from architecture diagrams to the relevant ADRs.


Output Format

When recommending an AWS architecture pattern, produce the following:

Architecture Summary

Workload: [name and description]
Tier:     [1 / 2 / 3] -- [SLA target: 99.99% / 99.9% / 99.5%]
Pattern:  [name, e.g., "Event-Driven Microservices", "Three-Tier Web", "Serverless API"]
Region:   [primary region] + [DR region if applicable]

Service Selection Decision Matrix

| Dimension | Selected Service | Considered Alternatives | Rationale |

|-----------|-----------------|------------------------|-----------|

| Compute | ECS Fargate | Lambda, EKS | Request duration > 15 min; team lacks k8s expertise |

| Database | Aurora PostgreSQL | RDS PostgreSQL, DynamoDB | Complex joins required; Serverless v2 for variable load |

| Cache | ElastiCache Redis | DAX, CloudFront | Session state + rate limiting; Redis data structures needed |

| Messaging | SQS + SNS fan-out | Kinesis, EventBridge | < 1,000 events/sec; no replay requirement |

| API | API Gateway HTTP API | REST API, ALB | No transform needed; lowest cost per request |

Architecture Diagram (ASCII)

Internet
    |
[CloudFront] -- [WAF]
    |
[ALB -- 3 AZs]
    |
[ECS Fargate -- Private App Subnets]
    |              |
[ElastiCache]  [SQS Queue]
    |              |
[Aurora PostgreSQL]  [ECS Worker -- Private App Subnets]
[Multi-AZ -- Private Data Subnets]

Key Configuration Parameters

# ECS Service configuration highlights
ecs_service:
  desired_count: 3
  deployment_circuit_breaker: true
  auto_scaling:
    min_capacity: 3
    max_capacity: 20
    target_cpu: 60
    scale_in_cooldown: 300    # seconds -- conservative to avoid thrash
    scale_out_cooldown: 60    # seconds -- aggressive to absorb spikes

# RDS Aurora Serverless v2
aurora:
  engine: aurora-postgresql
  engine_version: "15.3"
  serverless_v2:
    min_acu: 0.5
    max_acu: 32               # 32 ACU = ~64 GB RAM -- size to expected peak
  multi_az: true
  backup_retention_days: 7
  deletion_protection: true

# SQS Queue
sqs_queue:
  visibility_timeout: 300     # 5x expected processing time
  message_retention: 1209600  # 14 days
  dlq:
    max_receive_count: 3
    retention: 1209600

Cost Estimate

| Service | Configuration | Estimated Monthly Cost |

|---------|--------------|----------------------|

| ECS Fargate | 3 tasks @ 1vCPU/2GB, ~50% utilization | $45 |

| Aurora Serverless v2 | avg 2 ACU, Multi-AZ | $175 |

| ElastiCache Redis | cache.r7g.large, 1 replica | $165 |

| SQS | 10M requests/month | $4 |

| ALB | 1 ALB, 10 LCUs | $22 |

| Total | | ~$411/month |

Security Checklist

Operational Runbook Outline

## [Service Name] Runbook

### Health Check
- URL: GET /health -- expected 200 within 2 seconds
- CloudWatch Dashboard: [link]

### Scaling
- ECS auto-scales at 60% CPU -- no manual action needed
- If DynamoDB throttles: check CloudWatch ThrottledRequests; increase provisioned capacity or switch to on-demand

### Common Failure Modes
1. Database connection exhaustion -- check RDS max_connections; add RDS Proxy if Lambda or many ECS tasks
2. SQS DLQ messages accumulating -- check CloudWatch alarm; inspect DLQ messages for error pattern; fix and redrive
3. Lambda cold starts causing timeouts -- enable Provisioned Concurrency for p99 latency-sensitive paths

### Rollback Procedure
1. CodeDeploy console -- select deployment -- click Stop and Roll Back
2. ECS: update service to previous task definition revision (revision N-1)
3. Database: Aurora point-in-time restore if data corruption; RTO ~15-30 minutes

Rules

  1. Never deploy application or database resources in public subnets. Public subnets are exclusively for load balancers, NAT Gateways, and jump boxes. Every year, data breaches occur from RDS instances accidentally placed in public subnets with overly permissive security groups.
  1. Never use SQS FIFO queues by default. FIFO queues cap throughput at 3,000 TPS with batching and are 30% more expensive than Standard. Most workloads do not require strict ordering -- use Standard queues and design consumers to be idempotent instead.
  1. Never store AWS credentials on compute resources. EC2 instance profiles, ECS task roles, and Lambda execution roles provide credentials automatically via the metadata service (IMDS). Any access key in code, environment variables, or baked into an AMI is a security violation. Enable IMDSv2 on all EC2 instances to prevent SSRF-based credential theft.
  1. Always size Lambda memory based on profiling, not intuition. Lambda charges on duration × memory. A function at 512 MB running for 2,000ms costs the same as 1,024 MB running for 1,000ms, but the higher-memory version may deliver better user experience. Use AWS Lambda Power Tuning (open-source Step Functions state machine) to find the optimal memory setting for each function.
  1. Never create VPCs with overlapping CIDR ranges. Once a VPC is created, the CIDR cannot be changed without destroying and recreating it. Plan a non-overlapping address space up front using RFC 1918 ranges -- document the organization-wide CIDR allocation. Overlapping CIDRs make VPC peering and Transit Gateway routing impossible.
  1. Always set DLQs on every SQS queue, SNS subscription, Lambda async invocation, and EventBridge rule. Without DLQs, failed messages are silently discarded after exhausting retries. Every message lost in a DLQ-less queue is a business event that disappeared without investigation.
  1. Never use a single AWS account for all environments. Production, staging, development, and security/audit should be separate AWS accounts managed via AWS Organizations. This provides billing separation, blast radius containment (a misconfigured dev IAM policy cannot affect prod), and cleaner compliance boundaries.
  1. Always set explicit log retention periods on all CloudWatch Log Groups. The default retention is "never expire." A high-traffic service can accumulate thousands of dollars per month in CloudWatch Logs storage costs without retention policies. Set retention at Log Group creation time via IaC.
  1. Never choose Lambda for workloads with sustained high concurrency and cold start sensitivity. Lambda cold starts range from 100ms (Python/Node.js, no VPC) to 1,500ms+ (Java in VPC). For APIs requiring < 50ms p99 latency under sustained load, ECS Fargate with pre-warmed containers is the correct choice -- even if Provisioned Concurrency is configured, it adds cost and complexity without matching container warm performance.
  1. Always use Graviton-based instances for new workloads unless a specific dependency requires x86. Graviton3 instances (c7g, m7g, r7g, t4g) deliver 20-40% better price-performance than equivalent x86 instances. Aurora, ElastiCache, and Fargate all support Graviton. The migration path from x86 is low-risk for most containerized workloads -- test in staging first, but default to Graviton.

Edge Cases

Workload Exceeds Single-Region Capacity or Requires < 1 Minute RTO

For workloads with zero-downtime requirements across region failures, implement active-active multi-region:

Lambda Function Hitting Concurrency Limits During Traffic Spikes

Default Lambda concurrency limit is 1,000 per region (shared across all functions). A traffic spike can exhaust this limit, causing throttling on unrelated functions.

RDS Connection Exhaustion from Lambda or Many Microservices

Lambda functions create a new database connection on each cold start. At 1,000 concurrent Lambda executions, this creates 1,000 simultaneous connections -- exceeding the max_connections of even a db.r6g.2xlarge (approximately 1,000 connections at the PostgreSQL default).

S3 Eventual Consistency Causing Data Pipeline Race Conditions

S3 is strongly consistent for new PUT and DELETE operations since December 2020, but upstream assumptions about eventual consistency often appear in legacy code and documentation.

Data Transfer Costs Exceeding Compute Costs

AWS charges for data transfer out of a region to the internet and across regions. In data-intensive architectures, transfer fees can exceed compute and storage costs.

Microservices with Shared Database Becoming a Bottleneck

The single shared database anti-pattern -- multiple microservices sharing one RDS cluster -- creates tight coupling and a single point of failure for independent services.

Managing Blast Radius in Multi-Tenant SaaS Architectures

When one tenant's workload can degrade service for all other tenants (the "noisy neighbor" problem):


Example

Input: "We're building a B2B SaaS platform for document processing. Users upload PDFs (up to 50 MB) via a web app, our system extracts text and metadata using a third-party OCR API, stores the results, and makes them searchable. We expect 1,000 uploads/day at launch, growing to 100,000/day in 18 months. Team of 4, nobody has Kubernetes experience. We need GDPR compliance. Budget is $2,000/month initially. What architecture pattern do you recommend?"

Output:


Architecture Summary

Workload: B2B SaaS Document Processing Platform
Tier:     2 -- 99.9% availability SLA
Pattern:  Async Worker Pipeline with Serverless API and S3 Storage
Region:   eu-west-1 (primary) -- GDPR data residency requirement
DR:       eu-central-1 (S3 replication only at launch; promote to active-passive in 18 months)

Rationale for Pattern Selection

This workload is a classic async pipeline pattern, not a real-time API pattern:

The pattern: API Gateway receives uploads -- writes to S3 -- SQS triggers ECS workers -- workers call OCR API -- results stored in RDS Aurora + OpenSearch -- search served via API Gateway.


Service Selection Decision Matrix

| Dimension | Selected Service | Considered Alternatives | Rationale |

|-----------|-----------------|------------------------|-----------|

| Upload ingestion | API Gateway HTTP API + S3 presigned URLs | ALB direct, API Gateway REST API | Presigned URLs bypass API Gateway for large files (no 10 MB limit); HTTP API for metadata submission |

| File storage | S3 eu-west-1, SSE-KMS | EFS, direct disk | Object storage native for documents; KMS for GDPR encryption audit trail |

| Async trigger | S3 Event Notification -- SQS | Lambda direct, SNS | Decouples ingestion from processing; SQS buffers during OCR API rate limit periods |

| Worker compute | ECS Fargate | Lambda, EKS | Processing takes up to 30 seconds (Lambda 15-min limit ok, but cold starts add latency); no k8s expertise |

| Results database | Aurora PostgreSQL Serverless v2 | RDS PostgreSQL, DynamoDB | Relational metadata (users, documents, jobs); Serverless v2 scales to zero at 0.5 ACU overnight |

| Search | Amazon OpenSearch Serverless | RDS full-text, Elasticsearch on EC2 | Purpose-built full-text; Serverless avoids managing cluster capacity |

| Cache | ElastiCache Redis | CloudFront, DAX | Session storage + API rate limiting against OCR vendor; Redis TTL for recent search results |

| API layer | API Gateway HTTP API | REST API, ALB | No transformation needed; $1/million requests; supports JWT auth |

| Auth | Cognito User Pools | Auth0, custom JWT | GDPR-compliant IdP in EU region; built-in MFA; integrates natively with API Gateway |


Architecture Diagram (ASCII)

Web App (React)
    |
    |-- POST /documents/upload-url --> [API Gateway HTTP API] -- [Cognito JWT authorizer]
    |                                         |
    |                                   [Lambda - generate presigned URL]
    |                                         |
    |<------- presigned S3 URL ---------------+
    |
    |-- PUT <presigned URL> --------> [S3: document-uploads-bucket (eu-west-1)]
                                            |
                                  [S3 Event Notification]
                                            |
                                       [SQS Queue]
                                     (DLQ configured)
                                            |
                               [ECS Fargate Worker -- Private Subnet]
                                   (scales 1-20 tasks on SQS depth)
                                            |
                              +-------------+-------------+
                              |                           |
                    [Third-party OCR API]      [S3: document-results-bucket]
                     (external HTTPS)          (processed text, SSE-KMS)
                              |
                    [Aurora PostgreSQL]      [OpenSearch Serverless]
                    (job metadata,            (full-text index of
                     user records,             extracted document text)
                     Serverless v2)
                              |
                    [ElastiCache Redis]
                    (session cache,
                     search result TTL)

GET /documents/search --> [API Gateway] --> [Lambda search handler]
                                                    |
                                         [OpenSearch Serverless]
                                         [Aurora PostgreSQL]
                                         [ElastiCache Redis - TTL 60s]

Key Configuration Parameters

# S3 Buckets
s3_uploads_bucket:
  region: eu-west-1
  versioning: enabled             # required for GDPR erasure (delete specific version)
  encryption: SSE-KMS
  kms_key: aws/s3                 # customer-managed KMS key for audit trail
  lifecycle_rules:
    - id: delete_raw_after_90_days
      expiration_days: 90         # raw uploads deleted after processing; GDPR data minimization
  block_public_access: true
  replication:                    # DR replication to eu-central-1
    destination: s3://document-uploads-backup-eu-central-1
    rule: entire_bucket

s3_results_bucket:
  region: eu-west-1
  encryption: SSE-KMS
  block_public_access: true
  lifecycle_rules:
    - id: delete_results_on_account_deletion
      tag: gdpr_erasure_pending   # application tags objects; lifecycle deletes

# SQS Queue
document_processing_queue:
  visibility_timeout: 180         # 3x max expected processing time (60s OCR + buffer)
  message_retention: 1209600      # 14 days -- allows re-processing on worker deploy
  receive_message_wait_time: 20   # long polling -- reduces empty receive calls
  redrive_policy:
    dead_letter_queue: document_processing_dlq
    max_receive_count: 3          # 3 failures before DLQ; avoids poison-pill documents

document_processing_dlq:
  message_retention: 1209600
  cloudwatch_alarm:
    metric: ApproximateNumberOfMessagesVisible
    threshold: 1
    alarm_action: sns_pagerduty_p2  # any DLQ message warrants investigation

# ECS Worker Service
ecs_worker_service:
  launch_type: FARGATE
  task_definition:
    cpu: 1024                     # 1 vCPU -- OCR API calls are I/O bound, not CPU bound
    memory: 2048                  # 2 GB -- accommodates 50 MB PDF loading in memory
    architecture: ARM64           # Graviton -- 20% better price-perf for I/O bound tasks
    container:
      image: ecr/document-worker:latest
      environment:
        LOG_LEVEL: INFO
        OCR_API_TIMEOUT: 45       # seconds
      secrets:
        OCR_API_KEY: arn:aws:secretsmanager:eu-west-1:123456789012:secret:ocr-api-key
  auto_scaling:
    min_capacity: 1
    max_capacity: 20
    scaling_policy:
      metric: sqs_messages_per_task   # custom metric: SQS depth / running task count
      target_value: 5                 # 5 messages per task before scaling out
      scale_in_cooldown: 300
      scale_out_cooldown: 30

# Aurora PostgreSQL Serverless v2
aurora_postgresql:
  engine_version: "15.4"
  serverless_v2_config:
    min_acu: 0.5                  # scales to near-zero overnight (GDPR: no idle cost)
    max_acu: 8                    # 8 ACU = ~16 GB RAM -- sufficient for 100K docs/day
  instances:
    - role: writer
      instance_class: db.serverless
    - role: reader
      instance_class: db.serverless
  multi_az: true
  backup_retention_days: 30       # GDPR: 30-day point-in-time recovery
  deletion_protection: true
  storage_encrypted: true
  performance_insights: true
  parameter_group:
    max_connections: 200          # use RDS Proxy to multiplex ECS + Lambda connections

rds_proxy:
  engine_family: POSTGRESQL
  idle_client_timeout: 1800
  connection_borrow_timeout: 30
  target: aurora_postgresql

# OpenSearch Serverless
opensearch_serverless:
  collection_type: SEARCH
  encryption_policy: aws_owned_key  # upgrade to customer-managed KMS for GDPR audit
  network_policy: vpc               # private access only -- no public endpoint
  data_access_policy:
    principal: ecs_worker_task_role
    permissions: [indices:data/write, indices:data/read]

# ElastiCache Redis
elasticache_redis:
  node_type: cache.t4g.small        # Graviton; 1.37 GB -- sufficient for session/cache
  num_cache_nodes: 2                # primary + replica for HA
  automatic_failover: true
  at_rest_encryption: true
  in_transit_encryption: true
  auth_token: true                  # Redis AUTH required

# Cognito User Pools
cognito_user_pool:
  region: eu-west-1                 # GDPR data residency
  mfa_configuration: OPTIONAL       # enforce MFA for admin roles via group policy
  password_policy:
    minimum_length: 12
    require_uppercase: true
    require_numbers: true
    require_symbols: true
  deletion_protection: ACTIVE
  advanced_security_mode: ENFORCED  # adaptive authentication; blocks compromised credentials

GDPR Compliance Architecture Notes

  1. Data residency: All services deployed in eu-west-1. S3 replication to eu-central-1 is within EU -- acceptable for GDPR. Confirm OCR third-party API processes data within EU -- if not, add contractual DPA or switch to a EU-hosted OCR service.
  1. Right to erasure: Documents are stored with a user-scoped prefix in S3 (s3://bucket/user-id/document-id/). On account deletion, trigger a Lambda that: (a) deletes all S3 objects for the user prefix, (b) deletes Aurora rows for the user, (c) deletes OpenSearch documents by user_id query, (d) flushes ElastiCache keys prefixed with user_id.
  1. Encryption: All data stores encrypted at rest with KMS. TLS 1.2+ enforced on all connections. CloudTrail logs all KMS key usage to S3 in eu-west-1.
  1. Audit trail: CloudTrail enabled across all regions with a dedicated S3 bucket in a separate security/audit account. CloudTrail cannot be disabled by the application account.
  1. Data retention: Raw uploads deleted after 90 days via S3 lifecycle policy. Processed results retained until user deletion or explicit GDPR erasure request.

Cost Estimate (Launch: 1,000 uploads/day)

| Service | Configuration | Est. Monthly Cost |

|---------|--------------|-------------------|

| API Gateway HTTP API | 1M requests/month | $1 |

| S3 (uploads + results) | 200 GB storage + PUT/GET operations | $12 |

| SQS | 1M messages/month | $1 |

| ECS Fargate | avg 2 tasks × 1vCPU/2GB, ARM64, ~8h/day active | $28 |

| Aurora PostgreSQL Serverless v2 | avg 1 ACU, Multi-AZ | $87 |

| RDS Proxy | 1 vCPU target DB | $11 |

| OpenSearch Serverless | 1 OCU search, 1 OCU index | $175 |

| ElastiCache Redis | cache.t4g.small × 2 nodes | $26 |

| Lambda (presigned URL + search) | 2M invocations/month | $3 |

| Cognito | 1,000 MAU | $0 (free tier) |

| CloudWatch, CloudTrail, X-Ray | standard usage | $25 |

| NAT Gateway | 2 AZs, ~50 GB/month | $35 |

| KMS | 2 keys + API calls | $2 |

| Total | | **~$406/

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.