惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Develop Code for Lambda | 🏗️ Build A Real-Time Data Processing Pipeline
Ntombizakhon · 2026-05-08 · via DEV Community

Exam Guide: Developer - Associate
🏗️ Domain 1: Development with AWS Services
📘 Task 2: Develop Code for Lambda

Lambda is the most heavily tested service on the DVA-C02. It is also perhaps, one of the most used and talked about services in general too, well after EC2 and S3. So, you need to know how to configure it, write code for it, handle errors, tune performance, and integrate it with practically every other AWS service.


📘Concepts

Lambda Execution Model

When you invoke a Lambda function, AWS:
1. Finds or creates an execution environment (container)
2. Loads your code and initializes it (cold start)
3. Runs your handler function
4. Keeps the environment warm for reuse (subsequent invocations skip step 2)

Code outside the handler runs once during cold start and is reused. This is why you initialize SDK clients and database connections outside the handler.

Key Configuration Parameters

Parameter Range Default Notes
Memory 128 MB – 10,240 MB 128 MB CPU scales proportionally with memory
Timeout 1s – 900s (15 min) 3s Max 15 minutes: use Step Functions or ECS for longer or Durable functions
Concurrency Reserved or Provisioned 1000/region Reserved = guarantee + cap; Provisioned = pre-warmed
Ephemeral storage 512 MB – 10,240 MB 512 MB /tmp directory for temporary files
Layers Up to 5 250 MB total unzipped (function + layers)

Invocation Types and Error Handling

Invocation Type Source Examples Retry Behavior Error Destination
Synchronous API Gateway, ALB No automatic retries caller handles it Caller gets the error
Asynchronous S3, SNS, EventBridge 2 automatic retries (3 total) DLQ or Lambda Destinations
Event source mapping SQS, Kinesis, DynamoDB Streams Retries until record expires or succeeds DLQ (SQS) or on-failure destination

Lambda Destinations vs DLQ

Feature DLQ Lambda Destinations
Captures success No Yes
Captures failure Yes Yes
Context included Minimal Full (request, response, error)
Supported targets SQS, SNS SQS, SNS, Lambda, EventBridge
Works with Async invocations Async invocations

Lambda Destinations are the modern approach and preferred over DLQs. DLQs are still valid for SQS event source mappings.

VPC Access

By default, Lambda runs in an AWS-managed VPC and can access the internet and public AWS services. When you attach Lambda to your own VPC:

Without VPC:  Lambda → Internet → AWS Services ✅  |  Lambda → Private RDS ❌
With VPC:     Lambda → Private RDS ✅  |  Lambda → Internet ❌ (needs NAT Gateway)
              Lambda → VPC Endpoint → AWS Services ✅

Enter fullscreen mode Exit fullscreen mode

Key Points:

1. VPC Lambda needs private subnets with a NAT Gateway for internet access
2. Use VPC endpoints (PrivateLink) to access DynamoDB, S3, SQS without NAT
3. Use RDS Proxy for connection pooling because Lambda can overwhelm databases with concurrent connections

Cold Starts

A cold start happens when Lambda creates a new execution environment. Strategies to reduce them:

1. Provisioned Concurrency: pre-warms environments (costs money when idle)
2. Keep deployment packages small: smaller packages initialize faster
3. Initialize outside the handler: SDK clients, DB connections, config
4. Use ARM (Graviton2): often faster and 20% cheaper

Kinesis And Lambda Key Settings

Setting What It Does Relevance
Batch size Records per invocation (max 10,000) Larger batches = fewer invocations
Batch window Wait time to fill batch (max 300s) Reduces invocations for low-traffic streams
Parallelization factor (1–10) Concurrent batches per shard Increases throughput without adding shards
Bisect batch on error Splits batch in half on failure Isolates the bad record
Starting position LATEST or TRIM_HORIZON LATEST = new only. TRIM_HORIZON = from beginning

🏗️ Build A Real Time Data Processing Pipeline

Now let's put these concepts into practice by building a Real-Time Data Processing Pipeline using Lambda:

  • A Lambda function with VPC access connecting to an RDS database
  • Lambda layers for shared dependencies
  • A DLQ (Dead Letter Queue) and Lambda Destinations for error handling
  • A Kinesis stream processor that transforms data in near real time
  • Performance tuning with memory configuration

This covers all the skills for this task: Lambda configuration, VPC access, error handling, event lifecycle, integrations, and performance tuning.

Prerequisites


Part I

Create and Configure a Lambda Function

Create the Function

Step 01: Open the Lambda

Step 02: **Click **Create function

Step 03: Create function
Choose Author from scratch

  • Function name: DataProcessor
  • Runtime: Python 3.12

Click Create function

✅Green banner: Successfully created the function "DataProcessor".

Before writing code, let's walk through the configuration tabs.

Step 04: Click the Configuration tab.
General configuration
Click Edit:

  • Memory: 256 MB (default is 128 MB)
  • Ephemeral storage: 512 MB (default)
  • Timeout: 0 min 30 sec (default is 3 seconds)

Click Save.

Lambda allocates CPU proportionally to memory. At 1,769 MB you get one full vCPU. Increasing memory from 128 MB to 256 MB doubles your CPU therefore your function might run in half the time, costing the same or less.

Step 05: Environment variables
Click Environment variablesEditAdd environment variable:

  • Key: LOG_LEVEL, Value: INFO
  • Key: STAGE, Value: dev

Click Save.

✅Green banner: Successfully updated the function "DataProcessor".

import os

# Access environment variables in your code
log_level = os.environ.get('LOG_LEVEL', 'INFO')
stage = os.environ.get('STAGE', 'dev')

Enter fullscreen mode Exit fullscreen mode

Lambda encrypts all environment variables at rest by default using an AWS managed KMS key. For extra security, you can use a customer managed KMS key and decrypt in your code.


Part II

Create a Lambda Layer

Layers let you share code and libraries across multiple functions. Let's create one with a utility module.

Build and Upload a Layer

Layers must be uploaded as a zip file.
We'll use AWS CloudShell: a browser-based terminal built into the AWS Console so that you don't need anything installed locally.

Step 01: Open CloudShell by clicking the terminal icon (>_) in the top navigation bar of the AWS Console next to the search bar

Step 02: Wait for it to initialize as it might take a few seconds the first time

Step 03:
Run these commands:

mkdir -p python
cat > python/utils.py << 'EOF'
"""
Shared utilities for Lambda functions.
This module is packaged as a Lambda Layer so multiple functions can use it.
"""
import json
import time
import random

def retry_with_backoff(func, max_retries=3, base_delay=0.5):
    """Retry with exponential backoff and jitter."""
    for attempt in range(max_retries + 1):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries:
                raise
            delay = base_delay * (2 ** attempt)
            jitter = random.uniform(0, delay)
            time.sleep(delay + jitter)

def format_response(status_code, body):
    """Standard API Gateway response format."""
    return {
        'statusCode': status_code,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(body, default=str)
    }
EOF

zip -r utils-layer.zip python/

Enter fullscreen mode Exit fullscreen mode

Step 04: Download the zip
Click Actions ▼ (top right of CloudShell) → Download file → type utils-layer.zip → click Download

Why the python/ folder? Lambda layers must follow a specific directory structure. For Python, your code must be inside a python/ folder in the zip. Lambda adds this path to sys.path automatically so your functions can import utils directly.

Step 05: Upload the Layer via Console
In the Lambda console, click Layers in the left sidebar

Step 06: Click Create layer

  • Name: shared-utils
  • Upload: Choose the utils-layer.zip file
  • Compatible runtimes - optional: Python 3.12 Click Create

✅Green banner: Successfully created layer shared-utils version 1.

Step 07: Attach the Layer to Your Function
Go back to the DataProcessor function
Scroll down to the Layers section
Click Edit

Step 08: Edit layers
Click Add a layer
Choose Custom layers
Select shared-utils
Version: 1
Click Add

Click Save

✅Green banner: Successfully updated the function "DataProcessor".

Step 09: Now you can use it in your function code:

from utils import format_response, retry_with_backoff

def lambda_handler(event, context):
    return format_response(200, {'message': 'Hello from DataProcessor'})

Enter fullscreen mode Exit fullscreen mode

A function can have up to 5 layers. The total unzipped size of the function + all layers can't exceed 250 MB. Layers are versioned and immutable. Each upload creates a new version.


Part III

Error Handling: DLQ and Lambda Destinations

Create a Dead Letter Queue

Step 01: Open the SQS console

Step 02: Click Create queue

  • Type: Standard
  • Name: data-processor-dlq

Click Create queue

✅Green banner: Queue data-processor-dlq created successfully

Step 03: Copy the Queue ARN

Step 04: Create a Success Queue (for Destinations)
Create another queue:

  • Name: data-processor-success

Copy the Queue ARN

Step 05: Lambda → DataProcessor → Configuration → Permissions → Click the Role name
Add permissionsAttach policies
Search for AmazonSQSFullAccess and attach it

Step 06: Configure the DLQ on the Lambda Function
Go back to the DataProcessor function
Configuration tab → Asynchronous invocationEdit

  • Maximum age of event: 1 h 0 min 0 sec
  • Retry attempts: 2
  • Dead-letter queue service ▼: Select Amazon SQS
  • Queue ▼: Select data-processor-dlq

Click Save

✅Green banner: Successfully updated the function "DataProcessor".

Destinations are the modern approach. They capture both success AND failure.

Step 07: Configure Lambda Destinations
Still in Asynchronous invocation, find the Destinations section
Click Add destination

Step 08: Add destination

  • Source: Asynchronous invocation
  • Condition: On success
  • Destination type: SQS queue
  • Destination: data-processor-success

Click Save

✅Green banner: Your changes have been saved.

Step 09: Click Add destination again

  • Source: Asynchronous invocation
  • Condition: On failure
  • Destination type: SQS queue
  • Destination: data-processor-dlq

Click Save

✅Green banner: Your changes have been saved.

Lambda Destinations are preferred over DLQs because:

  • Destinations capture both success and failure (DLQ only captures failure)
  • Destinations include more context (request payload, response, error details)
  • Destinations work with async invocations only (same as DLQ)
  • DLQs are still valid for SQS event source mappings

Test Error Handling

Step 10: Let's create a function that sometimes fails to see the error handling in action:

Deploy this code, then test it

import json
import random

def lambda_handler(event, context):
    """
    This function randomly fails to demonstrate error handling.
    When invoked asynchronously:
    1. First attempt fails → Lambda retries
    2. Second attempt fails → Lambda retries again
    3. Third attempt fails → Event goes to DLQ / failure destination
    """
    action = event.get('action', 'process')

    if action == 'fail':
        # Always fail — will end up in DLQ after 3 attempts
        raise Exception("Simulated failure for testing DLQ")

    if action == 'random':
        # 50% chance of failure
        if random.random() < 0.5:
            raise Exception("Random failure occurred")

    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Processed successfully', 'action': action})
    }

Enter fullscreen mode Exit fullscreen mode

Step 11: Click Test tab

Step 12: Test event

  • Test event action: Create new event
  • Invocation type: Synchronous
  • Event name: TestFailure
  • Even JSON:
{
  "action": "fail"
}

Enter fullscreen mode Exit fullscreen mode

Click Test

Executing function: failed

The function will fail. Since this is a synchronous test invocation, you'll see the error immediately. To test the DLQ flow, you need an asynchronous invocation (from S3, SNS, or EventBridge).


Part IV

Lambda with VPC Access

When Lambda needs to access private resources like RDS or ElastiCache, you attach it to a VPC. Let's walk through the configuration.

Understanding VPC Access

Without VPC:
  Lambda → Internet → AWS Services (DynamoDB, S3, SQS)  ✅
  Lambda → Private RDS                                    ❌

With VPC:
  Lambda → VPC → Private RDS                              ✅
  Lambda → VPC → Internet                                 ❌ (no NAT)
  Lambda → VPC → NAT Gateway → Internet                   ✅
  Lambda → VPC → VPC Endpoint → AWS Services              ✅

Enter fullscreen mode Exit fullscreen mode

Configure VPC Access (Console Walkthrough)

Step 01: Open the DataProcessor function
Configuration tab → VPCEdit

Step 02: Edit VPC
Select the default VPC
Select at least 2 private subnets (for high availability)
Select or create a security group that allows outbound traffic

Click Save

⚠️Important: The Lambda execution role needs the AWSLambdaVPCAccessExecutionRole managed policy.

Step 03: Connection Reuse Pattern

When connecting to databases from Lambda, initialize the connection outside the handler:

import os
import json
import boto3

# This runs ONCE during cold start, then reuses across warm invocations
# This is critical for database connections — you don't want to open
# a new connection on every single invocation
db_host = os.environ.get('DB_HOST')
db_name = os.environ.get('DB_NAME')

# In a real app, you'd initialize your database connection here
# connection = pymysql.connect(host=db_host, ...)

def lambda_handler(event, context):
    """
    The handler runs on every invocation.
    The connection above is reused across warm invocations.
    """
    # Use the connection...
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Connected to database'})
    }

Enter fullscreen mode Exit fullscreen mode

Always initialize SDK clients and database connections outside the handler. This code runs once during the cold start and is reused for subsequent warm invocations.
For RDS specifically, use RDS Proxy to manage connection pooling. Lambda can open hundreds of connections simultaneously, which can overwhelm a database.


Part V

Process Streaming Data with Kinesis

Let's build a real-time clickstream processor.

Create a Kinesis Data Stream

Step 01: Open the Kinesis console
Click Create data stream

  • Data stream name: clickstream
  • Capacity mode: On-demand

Click Create data stream

✅Green banner: Data stream clickstream successfully created

Step 02: Create the Stream Processor Function
Go to LambdaCreate function
Configure:

  • Function name: ClickstreamProcessor
  • Runtime: Python 3.12
  • Memory: 512 MB
  • Timeout: 60 seconds

Step 03: Paste this code

import json
import base64
from datetime import datetime

def lambda_handler(event, context):
    """
    Processes clickstream records from Kinesis in near real time.

    Key concepts for the exam:
    - Kinesis data is base64 encoded
    - Records come in batches
    - The partition key determines which shard receives the record
    - Use a high-cardinality partition key (like userId) for even distribution
    """
    processed = 0
    failed = 0

    print(f"Received {len(event['Records'])} records from Kinesis")

    for record in event['Records']:
        try:
            # Kinesis data is base64 encoded — decode it
            raw_data = base64.b64decode(record['kinesis']['data']).decode('utf-8')
            data = json.loads(raw_data)

            # Extract clickstream fields
            user_id = data.get('userId', 'anonymous')
            page = data.get('page', 'unknown')
            action = data.get('action', 'unknown')
            timestamp = data.get('timestamp', datetime.utcnow().isoformat())

            # Process the click event
            print(f"Click: user={user_id}, page={page}, action={action}, time={timestamp}")

            # In a real app, you'd:
            # - Aggregate metrics
            # - Write to DynamoDB or S3
            # - Trigger alerts for specific patterns

            processed += 1

        except Exception as e:
            print(f"Failed to process record: {str(e)}")
            failed += 1

    print(f"Batch complete: {processed} processed, {failed} failed")

    return {
        'statusCode': 200,
        'body': json.dumps({
            'processed': processed,
            'failed': failed
        })
    }

Enter fullscreen mode Exit fullscreen mode

Click Deploy

✅Green banner: Successfully updated the function "ClickstreamProcessor".

Step 04: Add Permissions
The Lambda execution role needs permission to read from Kinesis:
Go to ConfigurationPermissions → click the role name
Add permissionsAttach policies
Search for and attach AmazonKinesisReadOnlyAccess

Step 05: Connect Kinesis to Lambda
In the ClickstreamProcessor function, click Add trigger

Step 06: Add trigger
Select a source ▼: Kinesis

  • Kinesis stream: clickstream
  • Batch size: 100
  • Starting position: Latest
  • Batch window: 5
  • On-failure destination: ``
  • Retry attempts: 3
  • Split batch on error: ✔ enabled
  • Concurrent batches per shard: 10

Click Add

✅Green banner: The trigger clickstream was successfully added to function ClickstreamProcessor.

Key Kinesis + Lambda settings:

  • Batch size: how many records per invocation (max 10,000)
  • Batch window: how long to wait to fill the batch (max 300s)
  • Parallelization factor: (1–10) process multiple batches per shard concurrently
  • Bisect batch on error: splits the batch in half on failure to isolate the bad record
  • Starting position: LATEST (new records only) or TRIM_HORIZON (from the beginning)

Step 07: Test with Sample Data
Send test records to the stream:
Open the Kinesis console → click clickstream

Step 08: clickstream
Click Data viewer tab
Or use the AWS CLI to send test data:

`shell
aws kinesis put-record \
--stream-name clickstream \
--partition-key "USER-001" \
--data '{"userId":"USER-001","page":"/products/laptop","action":"view","timestamp":"2026-04-24T10:00:00Z"}'
`

Step 09: Check the ClickstreamProcessor CloudWatch logs to see the processed records


Part VI

Performance Tuning

Memory vs Duration Experiment

Let's see how memory affects performance:

Step 01: Open the ClickstreamProcessor function

Step 02: ConfigurationGeneral configurationEdit
Set Memory to 128 MBSave

Step 03: Run a test → note the Duration and Max Memory Used in the execution results

`json
{
"Records": [
{
"kinesis": {
"data": "eyJ1c2VySWQiOiJVU0VSLTAwMSIsInBhZ2UiOiIvcHJvZHVjdHMvbGFwdG9wIiwiYWN0aW9uIjoidmlldyIsInRpbWVzdGFtcCI6IjIwMjYtMDQtMjRUMTA6MDA6MDBaIn0="
},
"eventSource": "aws:kinesis",
"eventSourceARN": "arn:aws:kinesis:us-east-1:123456789012:stream/clickstream"
},
{
"kinesis": {
"data": "eyJ1c2VySWQiOiJVU0VSLTAwMiIsInBhZ2UiOiIvY2hlY2tvdXQiLCJhY3Rpb24iOiJjbGljayIsInRpbWVzdGFtcCI6IjIwMjYtMDQtMjRUMTA6MDE6MDBaIn0="
},
"eventSource": "aws:kinesis",
"eventSourceARN": "arn:aws:kinesis:us-east-1:123456789012:stream/clickstream"
}
]
}
`

Step 04: Change memory to 256 MB → test again

Step 05: Change to 512 MB → test again

Step 06: Change to 1024 MB → test again

You'll typically see:

Memory Duration Billed Duration Cost per Invocation
128 MB ~200ms 200ms Low per-ms, but slow
256 MB ~110ms 110ms Sweet spot for many functions
512 MB ~60ms 60ms Faster, slightly more per-ms
1024 MB ~55ms 55ms Diminishing returns

The sweet spot is where increasing memory no longer significantly reduces duration.

Step 07: Concurrency Settings
ConfigurationConcurrency and recursion detection
ConcurrencyEdit

Step 08: Edit concurrency

  • USe unreserved account concurrency: Uses the shared regional pool (default 1000)
  • Reserve concurrency: Guarantees capacity AND caps the function

Select Reserve concurrency: 50

Click Save

✅Green banner: Your changes have been saved.

This means:

  • Your function is guaranteed 50 concurrent executions
  • It can never exceed 50 (acts as a throttle)
  • The remaining 950 are available for other functions

Reserved concurrency is free and serves two purposes: guaranteeing capacity AND protecting downstream services from being overwhelmed. Provisioned concurrency costs money even when idle but eliminates cold starts.


🏗️ What You Built | 📘Exam Concepts Recap

What You Did Exam Concept
Created a Lambda function and configured memory/timeout Lambda configuration parameters
Built and attached a Lambda Layer Sharing code across functions, layer structure and limits
Set up a DLQ and Lambda Destinations Async error handling, event lifecycle
Used --invocation-type Event to trigger async flow Synchronous vs asynchronous invocation types
Attached Lambda to a VPC with subnets and security group VPC access for private resources (RDS, ElastiCache)
Initialized SDK clients outside the handler Connection reuse, cold start optimization
Created a Kinesis stream and connected it to Lambda Real-time data processing, event source mappings
Configured batch size, batch window, parallelization factor Kinesis + Lambda tuning for throughput
Enabled bisect batch on error Isolating bad records in stream processing
Changed memory settings and compared Duration Performance tuning, memory = CPU relationship
Set reserved concurrency Throttling, capacity guarantees, protecting downstream services

⚠️ Clean Up Protocol

1. Lambda → Delete DataProcessor, ClickstreamProcessor
2. Lambda Layers → Delete shared-utils
3. Kinesis → Delete clickstream stream
4. SQS → Delete data-processor-dlq, data-processor-success
5. IAM → Delete the Lambda execution roles
6. CloudWatch → Delete the log groups


Key Takeaways

  1. Memory = CPU: more memory means more CPU. Find the sweet spot where cost and performance balance.
  2. Initialize outside the handler: SDK clients, DB connections, config loading. Reused across warm invocations.
  3. Lambda Destinations > DLQ: Destinations capture success AND failure with more context.
  4. ReportBatchItemFailures for SQS, BisectBatchOnFunctionError for Kinesis to isolate bad records.
  5. VPC Lambda loses internet: needs NAT Gateway or VPC endpoints for AWS services.
  6. RDS Proxy for Lambda-to-RDS: manages connection pooling.
  7. Layers: up to 5 per function, 250 MB total unzipped, versioned and immutable.
  8. 15-minute timeout is the max: for longer tasks, use Step Functions or ECS.
  9. Provisioned concurrency: eliminates cold starts but costs money when idle.
  10. Kinesis parallelization factor" (1–10) lets you process multiple batches per shard.

Additional Resources


🏗️