Caching and Loosely Coupled, Event-Driven Architectures
Overview
Two patterns make systems scale and survive failure: caching (answer repeated questions without bothering the origin) and loose coupling (producers and consumers communicate through queues, topics and events so neither needs the other to be available).
Imagine a restaurant. The pass between kitchen and waiters is a queue: waiters can keep taking orders even if the kitchen is slow. A laminated menu at each table is a cache: customers do not ask the chef what dishes exist every time.
For DOP-C02 you must pick the right cache layer (edge, application, database) and messaging pattern (SQS, SNS, EventBridge, Kinesis, Step Functions), configure DLQs and retries, and explain how they improve availability and cost.
Key Concepts
- CloudFront caches at edge locations with TTLs, cache policies, origin request policies, Origin Shield and origin failover groups; invalidations or versioned object names refresh content.
- ElastiCache for Redis/Valkey and Memcached provide in-memory caching; Redis supports replication, Multi-AZ failover, persistence and Global Datastore; Memcached is simple and multi-threaded.
- MemoryDB for Redis is a durable in-memory primary database (multi-AZ transaction log) when you need Redis speed with durability, not just a cache.
- DynamoDB Accelerator (DAX) is a write-through cache for DynamoDB with microsecond reads and the same API.
- API Gateway caching stores responses per stage (0.5-237 GB) for a TTL; keep caching in front of Lambda for read-heavy APIs.
- SQS decouples with at-least-once (standard) or exactly-once processing within a dedupe window (FIFO); DLQs capture poison messages.
- SNS fans out to many subscribers (SQS, Lambda, HTTP, email) with filter policies; EventBridge routes events by pattern with schemas, archive/replay and cross-account buses.
- Kinesis Data Streams provides ordered, replayable streaming; Step Functions orchestrates multi-step workflows with retries and error handling.
Detailed Notes
Cache layers
| Layer | Service | What it caches | Invalidation |
|---|---|---|---|
| Edge | CloudFront | Static and dynamic HTTP responses | TTL, invalidation, versioned names |
| API | API Gateway cache | Method responses | TTL, flush stage cache |
| Application | ElastiCache | Computed objects, sessions, query results | Application logic (lazy loading, write-through) |
| Database | DAX, RDS read replicas | DynamoDB items/queries, relational reads | Write-through (DAX), replica lag |
Caching strategies: lazy loading (cache on miss; risk of stale data), write-through (update the cache on write; wasted memory if data is never read), TTL (bounds staleness). Choose Redis when you need persistence, replication, data structures or pub/sub; choose Memcached for simple multi-threaded object caching.
CloudFront resilience features
Origins:
- Id: primary
DomainName: primary-alb.us-east-1.elb.amazonaws.com
- Id: secondary
DomainName: dr-alb.us-west-2.elb.amazonaws.com
OriginGroups:
Quantity: 1
Items:
- Id: failover
FailoverCriteria:
StatusCodes: { Quantity: 3, Items: [500, 502, 503] }
Members:
Quantity: 2
Items: [ { OriginId: primary }, { OriginId: secondary } ]
Origin failover applies to GET/HEAD/OPTIONS requests. Use Origin Access Control for S3 origins, signed URLs/cookies for private content, and Lambda@Edge or CloudFront Functions for lightweight request logic.
Messaging service comparison
| Need | Service | Key traits |
|---|---|---|
| Buffer and smooth load | SQS | Pull model, visibility timeout, DLQ, long polling |
| Strict ordering and dedupe | SQS FIFO | 300 msg/s (3000 with batching, higher with high throughput mode) per API action |
| Broadcast to many consumers | SNS (+SQS fan-out) | Push, filter policies, FIFO topics |
| Route events by content, SaaS and AWS sources | EventBridge | Rules, targets, archive/replay, Pipes, Scheduler |
| Ordered replayable stream | Kinesis Data Streams | Shards, retention up to 365 days, multiple consumers |
| Multi-step with branching/retry | Step Functions | Standard (long, exactly-once) vs Express (high-volume, at-least-once) |
Reliable consumer pattern
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 180 # at least 6x the Lambda timeout
RedrivePolicy:
deadLetterTargetArn: !GetAtt OrdersDLQ.Arn
maxReceiveCount: 5
Consumer:
Type: AWS::Lambda::EventSourceMapping
Properties:
EventSourceArn: !GetAtt OrdersQueue.Arn
FunctionName: !Ref ProcessOrder
BatchSize: 10
FunctionResponseTypes: [ReportBatchItemFailures]
ScalingConfig: { MaximumConcurrency: 20 }
Use ReportBatchItemFailures so only failed messages are retried, set MaximumConcurrency to protect the database, and alarm on ApproximateAgeOfOldestMessage and DLQ depth. Make consumers idempotent because standard queues and event sources deliver at least once.
Event-driven design guidelines
- Publish domain events to EventBridge and let consumers subscribe; avoid point-to-point synchronous calls across teams.
- Use SNS to SQS fan-out so each consumer has its own queue, retries and DLQ.
- Use S3 event notifications or EventBridge for object events; EventBridge offers filtering, archiving and cross-account delivery.
- Use Step Functions for orchestration with compensation (saga) rather than long chains of Lambda-to-Lambda calls.
- Handle backpressure with queue-based load levelling and reserved concurrency.
Failure modes
Cache stampede on mass expiry (add jitter to TTLs, request coalescing, Origin Shield), hot keys (replicate or shard), stale reads after writes (versioned keys), poison messages (DLQ plus redrive), and visibility timeout shorter than processing time (duplicate processing).
Real World Example
Scenario: a news site collapses during breaking-news spikes because every page view hits the CMS database. The team puts CloudFront in front with a 60 second TTL for article HTML and long TTLs for versioned assets, adds Origin Shield, and caches database lookups in ElastiCache for Redis.
Comment submissions move to an SQS queue consumed by Lambda with a DLQ and maximum concurrency, so a database slowdown no longer drops comments. Publishing an article emits an EventBridge event that fans out to search indexing, notification and analytics consumers.
Architecture Diagram
Reads are served from caches; writes are buffered and processed asynchronously.
- 1CloudFront answers repeated reads from edge locations.
- 2Cache misses reach API Gateway and the application.
- 3Writes are placed on an SQS queue with a dead-letter queue.
- 4Lambda consumers process in batches with limited concurrency.
- 5ElastiCache protects the database from repeated reads.
Best Practices
- ✓Cache at the layer closest to the user, and use TTLs with jitter plus versioned object names.
- ✓Put SQS between tiers that scale at different speeds and attach DLQs with redrive.
- ✓Make consumers idempotent and enable partial batch responses.
- ✓Use SNS+SQS fan-out or EventBridge for multiple subscribers instead of chaining calls.
- ✓Alarm on queue age, DLQ depth, cache hit ratio and evictions.
Common Interview Questions
Exam Tips
DOP-C02 focus
- "Microsecond reads for DynamoDB without code change" = DAX.
- "Redis as durable primary database" = MemoryDB.
- "Messages that keep failing" = DLQ with maxReceiveCount and alarm on depth.
- "Multiple independent consumers each with own retries" = SNS to SQS fan-out.
Finished this lesson?
0 of 44 lessons done · 0% of the course

