Profiling, Caching and Filter Policies for Optimisation
Overview
Optimisation starts with measuring. Amazon CodeGuru Profiler samples a running application to show which methods consume CPU and time. Combine it with X-Ray traces, Logs Insights and CloudWatch metrics to find bottlenecks, then fix them with caching, right-sized memory and concurrency, batching, and message filtering so consumers do less work.
It is like a doctor's workflow: check vital signs (metrics), take scans (traces and profiles), diagnose, then prescribe the smallest effective treatment instead of operating on a hunch.
This lesson closes the optimisation task statement: concurrency, profiling, minimum memory and compute, SNS subscription filter policies, application-level and edge caching, and reading logs for bottlenecks.
Key Concepts
- CodeGuru Profiler collects stack samples from Java and Python applications (agent or Lambda layer) and renders flame graphs with recommendations.
- CodeGuru Reviewer performs static analysis on pull requests; Profiler analyses runtime behaviour.
- Lambda memory controls CPU; use Power Tuning to choose the cheapest configuration at the performance target.
- Provisioned concurrency removes cold starts; reserved concurrency protects or caps a function.
- SNS filter policies let each subscription receive only matching messages, based on message attributes or message body.
- Caching layers: CloudFront (edge), API Gateway cache, application memory, ElastiCache, DAX.
- Batching (SQS batch size, Kinesis batching window,
BatchWriteItem) reduces per-item overhead and cost. - Identify bottlenecks by comparing X-Ray segment durations, Logs Insights percentiles and CloudWatch throttling and iterator-age metrics.
Detailed Notes
A structured approach
- Define the target (for example p99 below 300 ms).
- Measure: metrics for symptoms, traces for where time goes, profiler for why code is slow.
- Change one thing; re-measure.
- Keep the change only if it meets the target at acceptable cost.
| Symptom | Likely cause | Evidence | Remedy |
|---|---|---|---|
| High Lambda duration, CPU-bound | Too little memory | Duration drops with more memory | Raise memory, Power Tuning |
| Sporadic slow first requests | Cold starts | Init Duration in REPORT lines | Provisioned concurrency, SnapStart, smaller package |
| Slow downstream calls | Sequential I/O, no cache | X-Ray subsegments | Parallelise, cache, batch |
| Stream lag | Slow consumer | Kinesis IteratorAgeMilliseconds | Parallelisation factor, more shards |
| Throttles | Capacity or quota | Throttles, ThrottledRequests | Backoff, raise limits, on-demand tables |
CodeGuru Profiler
from codeguru_profiler_agent import with_lambda_profiler
@with_lambda_profiler(profiling_group_name="orders-profiling")
def handler(event, context):
return process(event)
Create a profiling group, give the role codeguru-profiler:ConfigureAgent and PostAgentProfile, and view the flame graph and recommendations (for example "regex compiled on every call"). Profiling adds low overhead (typically a few percent) and works for EC2, ECS, EKS and Lambda.
aws codeguruprofiler create-profiling-group --profiling-group-name orders-profiling \
--compute-platform AWSLambda
aws codeguruprofiler get-recommendations --profiling-group-name orders-profiling \
--start-time 2025-03-01T00:00:00Z --end-time 2025-03-02T00:00:00Z
Right-sizing Lambda
aws lambda update-function-configuration --function-name orders --memory-size 1536
aws logs start-query --log-group-name /aws/lambda/orders --start-time 1740787200 --end-time 1740873600 \
--query-string 'filter @type="REPORT" | stats avg(@duration), max(@maxMemoryUsed/1024/1024), pct(@duration,99) by bin(1h)'
If @maxMemoryUsed is far below the allocation and duration is flat across settings, reduce memory; if duration falls proportionally with memory, raising it often costs the same or less.
SNS subscription filter policies
Without filtering, every subscriber receives every message and discards what it does not need, wasting invocations. A filter policy on the subscription makes SNS deliver only matches.
aws sns subscribe --topic-arn arn:aws:sns:eu-west-1:111122223333:orders \
--protocol sqs --notification-endpoint arn:aws:sqs:eu-west-1:111122223333:billing \
--attributes '{"FilterPolicy":"{\"eventType\":[\"invoice\"],\"amount\":[{\"numeric\":[\">=\",100]}]}","FilterPolicyScope":"MessageAttributes"}'
The publisher sets message attributes (or the JSON body with FilterPolicyScope: MessageBody):
sns.publish(TopicArn=TOPIC, Message=json.dumps(order),
MessageAttributes={"eventType": {"DataType": "String", "StringValue": "invoice"},
"amount": {"DataType": "Number", "StringValue": "250"}})
Operators include exact match, prefix, anything-but, numeric ranges and exists. EventBridge rules and Lambda event source mappings have their own filtering, which also reduces invocations and cost.
Caching strategically
| Layer | Caches | Control |
|---|---|---|
| CloudFront | Static and cacheable API responses | Cache policy keys on headers, cookies, query strings; TTLs |
| API Gateway cache | Method responses per stage | TTL, cache key parameters, 0.5-237 GB |
| In-process | Config, secrets, clients | Reuse across warm invocations |
| ElastiCache / DAX | Query results, items | Lazy loading, write-through, TTL |
Cache what is read often and changes rarely; plan invalidation (TTL, versioned keys or events) and watch hit ratio. Avoid caching user-specific data in shared layers.
Reading logs for bottlenecks
Use Logs Insights to find slow requests and correlate with downstream timing logged inside the function; use X-Ray's service map for the slowest node and annotations to isolate customers or routes. In streams watch IteratorAge, in queues ApproximateAgeOfOldestMessage, and in DynamoDB ThrottledRequests and consumed versus provisioned capacity.
Batching and parallelism
Process SQS messages in batches with partial failure reporting; use BatchWriteItem with retries for unprocessed items; raise Kinesis parallelization factor up to 10 per shard; and use Step Functions Distributed Map or concurrency limits for large fan-out jobs.
Real World Example
An analytics API had p99 latency of 2.4 seconds. X-Ray showed time inside one function, and CodeGuru Profiler flagged a regular expression compiled on every call plus JSON re-parsing. After fixing code, adding an API Gateway cache for popular queries and raising memory to 1,536 MB (Power Tuning showed lower cost per request), p99 fell to 380 ms. An SNS filter policy also stopped the billing consumer from processing the 80 percent of events it ignored.
Architecture Diagram
Telemetry points to the bottleneck; targeted changes are verified by re-measuring.
- 1Metrics and logs reveal slow or throttled behaviour.
- 2X-Ray traces locate the slow segment.
- 3CodeGuru Profiler shows which code consumes time.
- 4A targeted change (cache, memory, filter, batching) is applied and re-measured.
Best Practices
- ✓Measure first: use metrics, traces and profiles before changing anything.
- ✓Tune Lambda memory with data (Power Tuning, REPORT logs).
- ✓Use filter policies so subscribers receive only relevant messages.
- ✓Cache at the right layer and track hit ratio and invalidation.
- ✓Batch and parallelise I/O, and handle partial failures correctly.
Common Interview Questions
Exam Tips
DVA-C02 focus
- 'Find which code is slow in production' means CodeGuru Profiler.
- Subscribers should get only some messages: SNS subscription filter policy.
- CPU-bound Lambda improves by increasing memory.
- Kinesis lag is shown by IteratorAgeMilliseconds.
Chapter quiz
Configuration, Testing, Release Management and Observability · 10 questions
1.A team wants to enable a new feature for 10 percent of users, increase it gradually and roll back automatically if error rates rise, without redeploying code. What should they use?
2.A Lambda function fetches AppConfig data on every invocation and hits API limits. What reduces calls and latency?
3.Which approach lets developers test a Lambda handler locally with a saved SQS-shaped payload in a Docker-based runtime?
4.A test publishes an EventBridge event and must verify that a downstream function wrote a record, without flaky fixed sleeps. What is best?
5.Front-end developers need responses from an API before the backend exists. Which API Gateway feature helps?
6.Builds occasionally fail because a public npm package is removed upstream. How can you make builds resilient and controlled?
7.A containerised service must be promoted from test to production with the exact image that passed tests, and nobody should overwrite the tag. What do you configure?
8.A containerised API intermittently receives traffic while still warming its cache. Which mechanism prevents routing to it until it is ready?
9.An operations team wants early warning before Lambda concurrency throttling affects customers. What should they do?
10.A billing consumer subscribed to a topic ignores most messages yet still gets invoked for all of them. What reduces cost without changing the publisher's topic?
0 of 10 answered
Finished this lesson?
0 of 46 lessons done · 0% of the course

