Serverless Architecture Overview
Serverless – Core Idea
- Serverless = minimal/no server management
- Concept more than technology; mainly a software architecture.
- You don’t manage the underlying servers, but they exist behind the scenes.
- Benefits: lower cost, reduced administrative overhead, less operational risk.
Key Characteristics
- Small, specialized functions
- Each function does a single task well.
- Functions start, execute, and stop quickly.
- Billing is per execution.
- Stateless & ephemeral
- Functions can run anywhere, independently.
- Event-driven
- Functions execute only when triggered.
- Consumption-based model: low idle costs.
- Managed services first
- Use services like S3, DynamoDB, Cognito instead of self-hosting.
- Code only what’s necessary.
- FaaS (Function-as-a-Service)
- Cheap, scalable compute for general tasks.
- AWS Lambda = main compute engine; avoids self-managed EC2 whenever possible.
Example: CatTube Serverless Architecture

- Frontend: Static website on S3 + client-side JS.
- Authentication:
- Third-party IDP (e.g., Google) → returns ID token.
- Cognito swaps ID token for temporary AWS credentials.
Video Upload Workflow
- Upload video → S3
Originalsbucket. - New object triggers Lambda function via S3 event.
- Lambda creates Elastic Transcoder jobs → outputs in
Transcodebucket. - Video metadata added to DynamoDB.
Media Access Workflow
- Client requests media → triggers Lambda function.
- Lambda loads metadata from DynamoDB + media from
Transcodebucket. - Lambda returns URLs for client to access media.
Key Points:
- Entire workflow is serverless.
- No EC2 or managed database servers.
- Event-driven + managed services = scalable, cost-efficient, maintainable.
Amazon SNS (Simple Notification Service) – Pub/Sub Messaging Service
Amazon SNS – Core Idea
- Serverless PUB-SUB messaging service
- Coordinates sending and delivery of messages to multiple destinations.
- Payloads ≤ 256 KB (good to remember: SNS is not for large files).
- Publicly accessible → connects over the internet.
- Heavily used for notifications across AWS (e.g., CloudWatch, CloudFormation).
SNS Architecture

- Regionally resilient → highly available, durable, and scalable.
- Secure → supports server-side encryption (SSE).
Key Entities
- SNS Topic – main entity
- Holds configuration and permissions.
- Enables 1-to-many communication:
- Publisher → sends messages to topic.
- Subscribers → receive messages.
- Supported subscriber types: HTTP(S), email, SQS, Lambda, SMS, mobile push.
- Entities can act as both publisher and subscriber.
- Topic Policy – resource policy defining who can read/write and supports cross-account access.
- Message Filters – allow subscribers to receive only relevant messages.
- Delivery Status & Retries – confirm message delivery and retry until success.
- Single SNS topic → multiple SQS queues (or other subscribers).
- Enables parallel processing of different workloads, e.g., handling different video sizes/bitrates in CatTube.
- Highly exam-relevant concept: fanout = topic → many subscribers.
Amazon API Gateway (APIGW) Basics
Application Programming Interface (API)
- Mechanism that enables communication between applications
- Example: issuing an HTTP GET request to
https://<URL>/cats/images/<your-cat-img-id>to retrieve an image stored on a remote system
- Example: issuing an HTTP GET request to
- OpenAPI Specification
- A widely adopted standard for defining APIs
- Simplifies API import and export processes
- Swagger UI: commonly used web interface for API visualization and testing
- Other API tools: Postman, Insomnia, Bruno
- Example: Swagger UI displaying an API interface

Amazon API Gateway (APIGW) – Key Concepts
- AWS-managed service used to build, publish, and manage APIs
- Serves as the entry point for client applications
- Controls API endpoints, resources, and HTTP methods
- Operates between client applications and backend integrations
- Integrations refer to backend services providing functionality
- Supports multiple API types:
- HTTP APIs
- REST APIs
- WebSocket APIs
- Serves as the entry point for client applications
- Service Characteristics
- Fully serverless
- Public-facing service that can expose AWS or on-premises systems
- Designed for high availability and scalability at the regional level
Features and Capabilities
- Security and Traffic Management
- Handles authorization
- Implements throttling to control request rates
- Provides caching mechanisms
- API Management
- Supports OpenAPI definitions
- Enables request and response transformations
- Service Integrations
- Direct integration with AWS services (e.g., DynamoDB, SNS)
- In many cases, removes the need for dedicated backend compute
- Cross-Origin Resource Sharing (CORS)
- Manages browser-based cross-domain access
- Allows web applications from one domain to call APIs hosted in another domain
- Example: JavaScript hosted in an S3 bucket invoking an API Gateway endpoint
- Migration Support
- Can act as a frontend layer while backend systems are being migrated or redesigned
Amazon API Gateway – Architecture

- Request Flow
- Authorization → validation → request transformation
- Backend integrations process the request
- Response transformation → preparation → return to client
Authentication Methods

- No Authentication
- Publicly accessible APIs
- Amazon Cognito User Pools
- Users authenticate via Cognito; API Gateway validates the token
- Lambda Authorizer
- Custom authorization using a Lambda function to validate tokens
- IAM-Based Authentication
- Uses AWS credentials provided in request headers
- Considered an advanced approach
Endpoint Types
- Edge-Optimized
- Requests are routed through the nearest CloudFront edge location
- Regional
- Designed for clients within the same AWS region
- Does not utilize CloudFront by default
- Private
- Accessible only within a VPC using interface endpoints
Stages

- An API configuration is deployed to a stage
- Each stage has:
- A unique endpoint URL
- Independent configuration settings
- Enables versioning (e.g., development, testing, production)
- Each stage has:
- Supports:
- Rollbacks for safe deployment management
- Isolation between environments
- Canary Deployments
- Routes a portion of traffic to a new version
- Allows gradual rollout and validation
- Can be promoted to the primary version after testing
Caching

- Improves performance by reducing calls to backend services
- Backend is only invoked on cache misses
- Key points:
- Configured at the stage level
- TTL set to 0 disables caching
- Cache data can be encrypted
Common HTTP Errors
- Important for troubleshooting and exam preparation
4XX – Client Errors (Invalid Requests)
- 400 – Bad Request
- Generic client-side error with multiple possible causes
- 403 – Forbidden
- Access denied by authorizer or blocked by a Web Application Firewall (WAF)
- 429 – Too Many Requests
- Throttling limit exceeded; client must retry later
5XX – Server Errors (Backend Issues)
- 502 – Bad Gateway
- Invalid response returned from backend service (e.g., Lambda)
- 503 – Service Unavailable
- Backend service is unavailable or down
- 504 – Gateway Timeout
- API Gateway timeout limit is 29 seconds
- Requests must complete within this limit, regardless of backend timeout settings
AWS Step Functions Basics
AWS Lambda – Limitations
- Lambda is a Function-as-a-Service (FaaS) offering with a maximum execution time of 15 minutes
- Not suitable for running full, long-lived applications within a single function
- Chaining multiple functions can simulate stateful behavior
- However, this approach is generally discouraged
- Does not scale efficiently
- Increases architectural complexity
- Lambda execution environments are stateless
- Execution context and data are not preserved between runs
- However, this approach is generally discouraged
- These constraints are intentionally designed
- Reinforces the idea that Lambda is optimized for short-lived, event-driven workloads
- Understanding service limitations is critical for proper architectural decisions
AWS Step Functions – Key Concepts (State Machines)
- Service used to orchestrate long-running, serverless workflows
- Workflows are defined using State Machines
- Helps overcome Lambda limitations such as execution time constraints
- Example use case:
- Retail order processing systems (e.g., large-scale e-commerce platforms)
- Processes may span hours or days
- Require coordination across multiple steps and services
- Retail order processing systems (e.g., large-scale e-commerce platforms)
- Workflow Types:
- Standard Workflows
- Maximum duration of up to 1 year
- Suitable for long-running and durable processes
- Express Workflows
- Maximum duration of up to 5 minutes
- Optimized for high-volume, short-duration workloads
- Easier retry handling for failed executions
- Common use cases include data processing and event-driven pipelines
- Standard Workflows
AWS Step Functions – State Machines (SM)
- A State Machine is the core construct of Step Functions
- Represents a serverless workflow: START → states → END
- Each state processes input, applies logic, and produces output
- Key Characteristics:
- Coordinates multiple steps and services within a workflow
- Maintains data flow between states
- Designed for complex, multi-service architectures
- Uses IAM roles to interact securely with other AWS services
- Invocation:
- Can be triggered by services such as API Gateway, IoT, EventBridge, Lambda, or manually
- Typically used for backend orchestration
- Amazon States Language (ASL)
- JSON-based language used to define state machines
- Enables creation, modification, and export of workflows
Common State Types in Step Functions
- Flow Control States
SUCCEEDandFAIL→ define workflow termination outcomesWAIT→ pauses execution until a time or duration is reachedCHOICE→ enables conditional branching based on inputPARALLEL→ executes multiple branches simultaneouslyMAP→ processes a list of items by iterating over each element
- Task State
- Represents a unit of work within the workflow
- Delegates execution to external services such as:
- Lambda, ECS, DynamoDB, SNS, SQS, AWS Batch, Glue, SageMaker, EMR, or other Step Functions workflows
- The state machine itself does not execute tasks directly; it coordinates execution across services
AWS Step Functions – Example Architecture

- Example: Pet Cuddle-o-Tron application
- Demonstrates a workflow where timed actions and notifications are triggered at different intervals
- Highlights orchestration across multiple services and time-based events
LAB: Building the Serverless Pet Cuddle-O-Tron
Pet Cuddle-O-Tron – Overview
End-State Architecture (Simplified – After Stage 5)
- Demonstrates a complete serverless workflow integrating frontend, API layer, orchestration, and messaging services

End-State Architecture (Extended – After Stage 7)
- Expands functionality to support multiple notification channels (email and SMS)

Stage 1: Configure Amazon Simple Email Service (SES)

- Amazon SES is used to send emails within the application
- Initially operates in sandbox mode
- Emails can only be sent to verified identities to prevent misuse
- Initially operates in sandbox mode
- Configuration steps:
- Create and verify two SES identities:
- Sender email address
- Receiver email address
- These identities must be explicitly authorized before use
- Create and verify two SES identities:
Stage 2: Configure Email Lambda Function

- A Lambda function is responsible for sending emails via SES
- Key setup steps:
- Create a Lambda execution role
- Permissions required:
- SES (send emails)
- SNS and Step Functions (if extended)
- CloudWatch Logs (for logging)
- Permissions required:
- Configure the Lambda function:
- Runtime: Python 3.9
- Assign the execution role
- Logic:
- Accept input parameters (email, message)
- Call SES to send email notifications
- Create a Lambda execution role

Stage 3: Configure Step Functions State Machine

- The State Machine acts as the orchestration layer of the application
- Controls workflow execution and service interactions
- Setup process:
- Create a State Machine IAM role
- Permissions:
- Invoke Lambda functions
- Publish to SNS
- Write logs to CloudWatch
- Permissions:
- Define the State Machine:
- Type: Standard
- Logging: Enabled (ALL)
- Workflow logic:
WAITstate delays execution based on inputTASKstate invokes the email Lambda functionPASSstate completes execution
- Create a State Machine IAM role
- The State Machine manages the sequence and data flow between components
Stage 4: Configure Backend API (API Gateway + Lambda)

- The backend exposes functionality through an API
- Architecture:
- API Gateway acts as the entry point
- A Lambda function processes requests and triggers the State Machine
- Implementation steps:
- Create API Lambda function
- Accepts input from API Gateway
- Validates required parameters
- Starts State Machine execution
- Create API in API Gateway:
- Type: REST API
- Endpoint type: Regional
- Configure API components:
- Resource:
/petcuddleotron - Method:
POST - Integration: Lambda function
- Enable Lambda Proxy Integration
- Resource:
- Enable CORS
- Allows browser-based clients hosted on different domains to call the API
- Deploy API:
- Stage name:
Prod - Capture the invoke URL for frontend integration
- Stage name:
- Create API Lambda function
Stage 5: Configure Frontend (S3 Static Website)

- The frontend is hosted using Amazon S3 static website hosting
- Setup steps:
- Create S3 bucket:
- Must have a globally unique name
- Public access enabled for static content
- Create S3 bucket:

- Configure bucket:
- Apply bucket policy to allow public read access
- Enable static website hosting
- Define
index.htmlas entry point

- Upload frontend assets:
- HTML, CSS, JavaScript, and image files
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
}
hr {
border-top: solid black;
}
div #error-message {
color: red;
font-size: 15px;
font-weight: bold;
}
div #success-message, #results-message {
color: green;
font-size: 15px;
font-weight: bold;
}
.form-signin {
max-width:480px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type=”Artist”] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type=”bottom”] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
- Frontend behavior:
- Collects user input (wait time, message, email)
- Sends request to API Gateway using JavaScript
var API_ENDPOINT = ‘REPLACEME_API_GATEWAY_INVOKE_URL’;
// if correct it should be similar to https://somethingsomething.execute-api.us-east-1.amazonaws.com/prod/petcuddleotron
var errorDiv = document.getElementById(‘error-message’)
var successDiv = document.getElementById(‘success-message’)
var resultsDiv = document.getElementById(‘results-message’)
// function output returns input button contents
function waitSecondsValue() { return document.getElementById(‘waitSeconds’).value }
function messageValue() { return document.getElementById(‘message’).value }
function emailValue() { return document.getElementById(’email’).value }
function clearNotifications() {
errorDiv.textContent = ”;
resultsDiv.textContent = ”;
successDiv.textContent = ”;
}
// When buttons are clicked, this is run passing values to API Gateway call
document.getElementById(’emailButton’).addEventListener(‘click’, function(e) { sendData(e, ’email’); });
function sendData (e, pref) {
e.preventDefault()
clearNotifications()
fetch(API_ENDPOINT, {
headers:{
“Content-type”: “application/json”
},
method: ‘POST’,
body: JSON.stringify({
waitSeconds: waitSecondsValue(),
message: messageValue(),
email: emailValue()
}),
mode: ‘cors’
})
.then((resp) => resp.json())
.then(function(data) {
console.log(data)
successDiv.textContent = ‘Submitted. But check the result below!’;
resultsDiv.textContent = JSON.stringify(data);
})
.catch(function(err) {
errorDiv.textContent = ‘Oops! Error Error:\n’ + err.toString();
console.log(err)
});
};
Stage 6: Test the Application
- Access the S3 website endpoint to load the frontend interface
- Test workflow:
- Input parameters:
- Wait time
- Message
- Email address
- Submit request:
- API Gateway receives request
- Lambda triggers State Machine
- State Machine invokes email Lambda
- Input parameters:
- Monitoring:
- Execution flow can be tracked via Step Functions logging
- Result:
- Email notification is delivered to the specified recipient
- Outcome:
- Fully functional serverless architecture with no infrastructure provisioning required
- Update frontend:
- Add phone number input
- Modify JavaScript to include phone parameter
- Allow optional email and phone inputs
- Update API Lambda:
- Ensure at least one contact method (email or phone) is provided
- Update State Machine:
- Introduce
CHOICEstate:- Email only
- SMS only
- Both email and SMS
- Use
PARALLELstate when both are required
- Introduce
- Result:
- Application supports multi-channel notifications
Stage 7 (Extended): Enable SMS-Based Notifications

- The initial Pet-Cuddle-o-Tron design supported notifying users via both email and SMS, but it was simplified to email-only. This stage restores the original dual-channel notification capability by adding SMS support through additional SNS setup and minor system enhancements.
- Important: SMS delivery via SNS is not covered by the AWS Free Tier, though costs remain low for minimal usage.
1. Set Up Simple Notification Service (SNS) for SMS
- Navigate to SNS → Mobile → Text messaging (SMS) → Sandbox destination phone numbers
- SNS begins in sandbox mode, similar to SES
- Add and verify a recipient phone number (AWS sends a verification code via SMS)
- For simplicity:
- Do not attach the number to SNS topics
- Do not configure a dedicated origination number
2. Create a Lambda Function for SMS Notifications
- Function name:
sms_reminder_lambda - Runtime:
Python 3.9 - Execution role: reuse the same role as
email_reminder_lambdaandapi_lambda - This function sends SMS messages using SNS based on input from the workflow:
import boto3, os, jsonsns = boto3.client('sns')def lambda_handler(event, context):
print("Received event: " + json.dumps(event))
sns.publish(
PhoneNumber=event['Input']['phone'],
Message=event['Input']['message']
)
return 'Success!'
3. Update Frontend to Include Phone Input
- Modify the static website to capture a phone number along with existing inputs
- Add a phone input field in
index.html - Update
serverless.jsto include:
function emailValue() { return document.getElementById('email').value || 'NO_EMAIL' }
function phoneValue() { return document.getElementById('phone').value || 'NO_PHONE' }
- Include both values in the API request payload:
body: JSON.stringify({
waitSeconds: waitSecondsValue(),
message: messageValue(),
email: emailValue(),
phone: phoneValue()
}),
- If no value is provided:
"NO_EMAIL"or"NO_PHONE"is sent- This allows the backend to determine the correct execution path
4. Update API Lambda Validation
- Add a validation check to ensure at least one contact method is provided:
checks.append(not (data['email'] == "NO_EMAIL" and data['phone'] == "NO_PHONE"))
- This prevents requests without any notification target
- Additional validation for email/phone formatting can be added if needed
5. Enhance Step Functions Workfow Logic
- Introduce a Choice state to determine the notification method:
EmailOnlySMSOnlyEmailAndSms
- Behavior:
- If only email is present → trigger email Lambda
- If only phone is present → trigger SMS Lambda
- If both are present → execute both in parallel
- The
EmailAndSmsstate uses parallel branches to invoke both Lambda functions simultaneously
6. Validate the Updated Workflow

- Test all possible input scenarios:
- No email → SMS only
- No phone → Email only
- Both provided → Email and SMS sent
- Confirm:
- Correct branching in Step Functions
- Successful message delivery via SNS
Stage 8: Resource Cleanup
- Remove all created AWS resources after completing the lab
- Prevents unnecessary charges
- Includes:
- Lambda functions
- API Gateway
- Step Functions
- SNS/SES configurations
- S3 bucket
Amazon SQS (Simple Queue Service) Basics
Amazon SQS (Simple Queue Service) – Overview
- Fully managed queuing service
- Enables asynchronous communication where producers push messages to a queue and consumers retrieve them through polling
- Supports two queue types based on ordering behavior:
- Standard → best-effort ordering, messages may be delivered out of sequence
- FIFO (First-In-First-Out) → guarantees strict ordering
- Designed for small payloads (up to 256 KB, similar to SNS)
- Smaller messages are easier to handle and scale
- For larger data, messages typically contain references (e.g., links to stored data)
- Managed entirely by AWS
- Serverless (no infrastructure management required)
- Accessible via public endpoints
- Built for regional high availability and scalability
- High throughput and performance
- One of the earliest AWS services, launched in 2004
Message Retrieval and Visibility
- Polling is the process of checking a queue for available messages
- Retrieved messages are not automatically removed
- Instead, they become temporarily hidden using the Visibility Timeout
- Messages are permanently deleted only when:
- The consumer explicitly deletes the message after successful processing
- The Visibility Timeout expires, making the message visible again if processing was not completed in time
- This approach ensures reliability:
- Messages can be retried by the same or different consumers if processing fails
Handling Failed Messages
- Messages that repeatedly fail processing can be moved to Dead-Letter Queues (DLQs)
- Allows separate handling and analysis of problematic messages
- Improves fault tolerance and troubleshooting
- Common Use Cases
- Decoupling system components
- Enabling scalable architectures
- Auto Scaling Groups and Lambda functions can scale based on queue depth
- Supporting distributed worker or background processing systems
Amazon SQS – Example Worker Pool Architecture

- The architecture revisits a media processing example using asynchronous queues
- ASG Web Tier
- Users upload source content
- The application stores the original file in an S3 bucket (
Master) - A message containing a reference to the file is sent to an SQS queue
- Processed outputs are later retrieved from another bucket (
Transcode) - Scaling is driven by application demand (e.g., CPU usage)
- ASG Worker Tier
- Continuously polls the SQS queue for tasks
- Scales based on queue depth:
- High queue length → scale out
- Low queue length → scale in (can scale to zero)
- Retrieves the original file, processes it into multiple formats, and stores results
- If processing fails:
- The message becomes visible again after the Visibility Timeout
- Another worker can retry the task
- The queue acts as a decoupling layer between web and worker tiers, allowing them to operate independently
Fanout Pattern with SNS and SQS

- Instead of sending messages directly to SQS:
- The producer publishes messages to an SNS topic
- The SNS topic distributes those messages to multiple SQS queues (subscribers)
- Each queue:
- Represents a different processing path (e.g., video quality variants)
- Scales independently with its own worker group
- This pattern is common with S3 event-driven designs:
- S3 generates a single event per object upload
- SNS distributes that event to multiple processing pipelines
Amazon SQS – Features
Standard vs FIFO Queue Tradeoffs
- Standard Queues
- At-least-once delivery
- No ordering guarantee
- Possible duplicate messages
- Highly scalable with high throughput
- FIFO Queues
- Exactly-once processing
- Guaranteed message order
- Lower throughput compared to Standard queues
Billing Model
- Charges are based on requests, not messages or API calls
- A single request can return:
- Up to 10 messages
- Up to 64 KB of data
- A single request can return:
- Large messages increase request usage:
- Example: a 256 KB message results in 4 billable requests
- Cost considerations:
- Frequent polling may return no messages, increasing cost unnecessarily
- Efficient system design balances responsiveness and cost, often using long polling
Polling Methods
- Short Polling
- Immediate response
- May return zero messages
- Long Polling
- Waits up to a specified duration (
ReceiveMessageWaitTimeSeconds, max 20 seconds) - Returns messages as soon as they are available
- Reduces empty responses and improves cost efficiency
- Waits up to a specified duration (
- Long polling is generally the recommended default
Security and Data Protection
- Messages can be retained for up to 14 days
- Encryption at rest using KMS (SSE)
- Encryption in transit via SSL/TLS
- Access control via:
- IAM identity policies
- Queue resource (policy-based) permissions
SQS – Standard vs FIFO Queue Types
SQS Queue ↔ Highway Analogy

- SQS queues are categorized based on how they handle message ordering:
- Standard (at-least-once delivery)
- FIFO (First-In-First-Out, exactly-once delivery)
- Understanding the tradeoffs is key, and a highway comparison helps visualize this:
- Messages are like cars
- Standard queues resemble multi-lane highways where vehicles can move freely and overtake
- FIFO queues resemble single-lane roads where movement is controlled and order is maintained
SQS Standard Queues
- At-least-once delivery model
- Limitations
- Ordering is not guaranteed; messages may arrive out of sequence
- Duplicate messages can occur if polled multiple times
- Applications must be designed to handle duplicates and unordered data
- Advantages
- Extremely high scalability and throughput
- Scaling is smooth and flexible as demand increases
- Comparable to adding more lanes to a highway to increase capacity
- Common Use Cases
- Decoupling distributed system components
- Worker-based processing systems
- Batch processing pipelines
SQS FIFO (First-In-First-Out) Queues
- Exactly-once processing model
- Requires the queue name to include the
.fifosuffix
- Requires the queue name to include the
- Advantages
- Strict preservation of message order
- No duplicate message delivery
- Limitations
- Lower throughput and scaling capacity compared to Standard queues
- Similar to how a single-lane road limits traffic flow
- Typical throughput:
- ~300 transactions per second without batching
- ~3000 messages per second with batching (up to 10 messages per request)
- Some regions support significantly higher throughput, especially with high-throughput FIFO mode
- Even with enhancements, performance is still below Standard queues
- Lower throughput and scaling capacity compared to Standard queues
- Common Use Cases
- Ordered workflows where sequence matters
- Command processing in strict order
- Step-by-step or iterative calculations (e.g., financial or order processing systems)
SQS – Delay Queues
SQS – Visibility Timeout

- Time window after a message is received during which it remains hidden from other consumers
- Configurable from 0 seconds to 12 hours (default is 30 seconds)
- Can be adjusted using the
ChangeMessageVisibilityAPI - Can also be set at the individual message level, overriding the queue default
- Useful for enabling retry mechanisms and fault recovery
- Message lifecycle with Visibility Timeout:
- A message is added to the queue using
SendMessage - A consumer retrieves it via
ReceiveMessage - Once retrieved, the Visibility Timeout begins, and the message becomes temporarily invisible
- If processing completes successfully → the message is deleted
- If processing fails or exceeds the timeout → the message becomes visible again and can be retried
- A message is added to the queue using
- Important behavior:
- Visibility Timeout only applies after a message has been received
- It controls reprocessing behavior, not initial delivery
- This is different from
DelaySeconds, even though both involve temporary invisibility
SQS – Delay Seconds

- Defines a delay before a message becomes visible for the first time
- Messages enter the queue in a hidden state and remain invisible until the delay expires
- During this period,
ReceiveMessagewill not return the message - Used to introduce a controlled delay before processing begins
- Configuration:
- Range: 0 seconds to 15 minutes (default is 0 seconds)
- A queue with a non-zero delay is considered a delay queue
- Message-level control:
- Initial delay can also be defined per message (message timer), overriding queue settings
- This allows fine-grained control over when specific messages become available
- Limitations:
- Per-message delay (message timers) is not supported for FIFO queues
- This restriction preserves strict ordering guarantees
- Queue-level delay (
DelaySeconds) is still supported for FIFO queues
- Per-message delay (message timers) is not supported for FIFO queues
- Key distinction:
DelaySecondscontrols when a message first becomes availableVisibilityTimeoutcontrols what happens after a message has been retrieved
SQS – Dead-Letter Queues (DLQs)
SQS Dead-Letter Queue (DLQ)

- Dedicated queue for handling failed or unprocessable messages
- Used to isolate messages that repeatedly fail during processing
- Prevents continuous retry cycles in the main queue
- Without a DLQ, failed messages may be retried many times within the retention window (up to 14 days), which is typically undesirable
- Redrive policy controls how messages are moved to a DLQ:
- Defines the source (SRC) queue to monitor
- Specifies the target DLQ where failed messages are sent
- Includes conditions for redriving messages, requiring a configured
maxReceiveCount
- A single DLQ can be associated with multiple source queues
- Each time a message is received from the source queue:
- Its
ReceiveCountincreases - Once
ReceiveCountreachesmaxReceiveCount, the message is transferred to the DLQ
- Its
- Common DLQ use cases:
- Trigger alerts when messages are moved to the DLQ
- Perform isolated troubleshooting and analysis (e.g., reviewing logs or payloads)
- Apply alternative or specialized processing for failed messages
SQS – Message Retention Period
- Defines how long messages are stored in a queue before being automatically removed
- Messages are deleted once the retention period expires
- Each message is assigned an enqueue timestamp upon arrival
- This timestamp is used to determine when the message should expire
- Important behavior with DLQs:
- The original enqueue timestamp is not reset when a message is moved to a DLQ
- Example:
- If a message spends 1 day in the source queue and the DLQ retention is 2 days
- It will only remain in the DLQ for the remaining 1 day
- Example:
- The original enqueue timestamp is not reset when a message is moved to a DLQ
- Best practice:
- Configure DLQs with a longer retention period than the source queue
- Ensures sufficient time for analysis and reprocessing of failed messages
Amazon Kinesis Data Streams Basics
Amazon Kinesis Data Streams (KDS) – Core Concepts
- Real-time data streaming platform
- Built to collect and process high volumes of data continuously from multiple sources
- Serverless, public, and regionally resilient, but shard scaling must be managed by the customer
- Data Stream = fundamental unit of Kinesis
- Producers write data into streams, consumers read data from streams
- Streams can scale from minimal throughput to very high volumes
- Data retention is time-bound (default 24 hours)
- Older data is automatically discarded
- Retention period can be extended up to 365 days at additional cost
- Amazon Data Firehose can export stream data to other services (e.g., S3) for long-term storage
- Supports multiple producers and multiple consumers, allowing fine-grained access
- Ideal for real-time analytics, dashboards, and monitoring
Kinesis Data Streams – Architecture

- Data flows from producers into streams, then consumers read from the streams
- Shards enable scaling
- Each shard provides:
- 1 MB/s data ingestion
- 2 MB/s data consumption
- More shards → higher throughput and higher costs
- Data is stored in Kinesis Data Records (max 1 MB per record)
- Scaling is linear: add shards to handle more data
- Each shard provides:
- Billing is based on:
- Number of shards
- Data retention window size
- Kinesis is relatively costly, intended for use cases that require real-time data streaming
SQS vs Kinesis
- Key distinction: Kinesis handles continuous, high-volume data streams, while SQS is for asynchronous message delivery
- SQS:
- Typically one producer group (e.g., WEB tier) and one consumer group (e.g., WORKER tier)
- Not intended for hundreds or thousands of sources sending data simultaneously
- Best for decoupling components and asynchronous task queues
- Messages are temporary; no rolling window for data retention
- Kinesis:
- Designed for massive, high-frequency data ingestion
- Examples: analytics, real-time monitoring, app clickstreams
- Supports multiple independent consumers
- Maintains a rolling window of data for temporary persistence
- Enables real-time streaming and processing
- Designed for massive, high-frequency data ingestion
Amazon Kinesis Video Streams – Real-Time Video Data Streaming
Amazon Kinesis Video Streams (KVS) – Core Concepts
- Real-time video streaming platform
- Captures live video or time-sequenced sensor data from producers, including:
- Video sources: security cameras, smartphones, drones, vehicles
- Sensor streams: audio, thermal imaging, depth sensors, RADAR
- Consumers can retrieve data frame-by-frame or in segments as needed
- Captures live video or time-sequenced sensor data from producers, including:
- Fully-managed AWS service
- Serverless, public, and regionally resilient
- Automatically scales with demand
- Data is persisted and encrypted both in-transit and at rest
- Access via API only
- Raw source data is not directly accessible
- Consumers interact with indexed and structured streams stored in KVS
- Integrates with other AWS services:
- Amazon Rekognition (for video and image analysis)
- Amazon Connect (e.g., voicemail or multimedia processing)
- Use cases:
- Event-driven video analytics pipelines
- Streaming from cameras or IoT devices
- For exam scenarios mentioning GStreamer or RTSP, KVS is the default choice
- GStreamer: multimedia pipeline framework for connecting multiple processing systems
- RTSP: protocol for transporting real-time multimedia streams over a network
Kinesis Video Streams – Example Video Surveillance Architecture (with Rekognition)

- Security cameras in a smart home stream video into a Kinesis Video Stream (KVS) in AWS, offloading local video processing
- Video streams feed into Amazon Rekognition Video for analysis (e.g., facial recognition, object detection)
- Rekognition outputs processed data to a Kinesis Data Stream (KDS) containing structured insights, such as identified faces or events
- Further automation: AWS Lambda can process each record and trigger notifications via SNS for events like unknown faces detected
Amazon Kinesis Data Firehose Basics
Amazon Data Firehose – Key Concepts
- Fully-managed data delivery service
- Moves and stores data into data lakes, data stores, and analytics platforms.
- By default, Kinesis Data Streams (KDS) does not retain data long-term
- Data is available only within its retention window; Firehose can persist it beyond that by delivering it elsewhere.
- Features:
- Managed by AWS
- Serverless, regionally redundant, and publicly accessible.
- Scales automatically, unlike KDS which requires shard management.
- Near real-time data delivery (~60s by default)
- Unlike KDS (~200ms), Firehose is not strictly real-time by default.
- Buffering can now be disabled for true real-time delivery if needed.
- On-the-fly data transformation using Lambda
- Processing may introduce some latency depending on complexity.
- Managed by AWS
- Billing model: Pay-as-you-go, based on the volume of data processed.
- Common use cases:
- Loading data into supported destinations.
- Persisting KDS data after its retention window.
- Transforming data format during delivery using Lambda.
Amazon Data Firehose – Architecture

- Supported data sources
- AWS services (CloudWatch Logs, CloudWatch Events)
- IoT devices
- Kinesis Data Streams
- Kinesis producers (KPL, Kinesis Agent)
- KPL = Kinesis Producer Library; the Agent is built on top of it.
- If streaming features of Kinesis aren’t required, data can be sent directly to Firehose.
- Supported destinations
- HTTP endpoints (for 3rd-party delivery)
- Splunk
- Amazon S3
- Amazon Redshift
- Amazon OpenSearch Service (formerly Elasticsearch Service)
- Data buffering for delivery
- By default, Firehose waits for 1 MB of data or 60 seconds before sending.
- AWS now allows disabling the buffer for true real-time delivery, though the default buffer is still active.
- Lambda transformation support
- Can use built-in blueprints for common transformations.
- Optional: retain raw data in an S3 backup bucket.
- Transformation may add latency.
- Redshift delivery specifics
- Firehose writes data to S3 first; Redshift then loads data via COPY.
- The process is managed automatically, but the S3 step is required.
Amazon Managed Apache Flink – Stream Processing Service (formerly Kinesis Data Analytics)
DISCLAIMER: Name Change from Amazon Kinesis Data Analytics
- This service was previously called Amazon Kinesis Data Analytics, where SQL was used for data transformations.
- It is no longer part of the Kinesis product family. The core engine is now Apache Flink, though SQL transformations are still supported.
- Reference: AWS Announcement
- Older lecture notes reference the previous naming but the service retains most functionality.
- Old summary (for context):
- Analyzes streaming data in real time, enabling actionable insights and immediate responses.
- Operates on high-throughput streaming data and transforms input using SQL (optionally with S3 reference data).
- Streams output to destinations such as dashboards or analytics systems.
- Typical use cases: time-series analytics (e.g., elections, esports), real-time dashboards, real-time security metrics.
Amazon Managed Service for Apache Flink – Overview
- Purpose: Real-time stream processing using Apache Flink.
- Acts between an input stream and an output stream, transforming data in transit.

- Supported sources:
- Kinesis Data Streams
- Data Firehose
- Amazon Managed Streaming for Apache Kafka (MSK)
- Optional static reference data from S3
- Supported destinations:
- Kinesis Data Streams
- Data Firehose (and its downstream destinations: HTTP, Splunk, OpenSearch Service, S3, Redshift)
- MSK
- Lambda
- S3
- Analytics tools
Stream Processing Architecture

- Input sources remain unchanged; only output streams are modified.
- In-application input streams function like tables, updated continuously to match the live input stream.
- Reference tables (from S3) contain static data that can enrich the input stream.
- Example: An esports stream sends live player data; static player metadata from S3 is joined to live data in real time for enhanced dashboards.
- Application code (SQL or Flink API) processes input and generates in-application output streams.
- Errors can be routed to an in-application error stream.
- Billing: Charged based on processed data volume; cost can be significant. Use only for workloads that need real-time stream processing.
- Typical use cases:
- Time-series analytics (elections, esports, etc.)
- Real-time dashboards (leaderboards, sports, games)
- Real-time metrics for security and operations teams
Amazon Cognito – User Authentication and Identity Management Service
Amazon Cognito – Overview
- Core AWS identity service: provides authentication, authorization, and serverless user management for web and mobile apps.
- Two main components:
- User pools – handle sign-in and issue JSON Web Tokens (JWTs).
- Identity pools – provide temporary AWS credentials to access AWS resources.
- Note: User pools and identity pools serve different purposes despite similar naming.
- Scalability: Supports unlimited users, far exceeding the 5,000 IAM user limit, making it suitable for large-scale applications.
Amazon Cognito – User Pools

- User directory: stores users like a database.
- Provides standardized sign-up/sign-in experiences. Authenticated users receive a JWT.
- Additional features: user management, customizable web UI, multi-factor authentication (MFA), and other security settings.
- Users can be internal or external (e.g., via social IDPs like Google or Facebook).
- JWTs:
- Prove the user has authenticated with the user pool.
- Can be used for authentication to self-managed servers or databases.
- Services like API Gateway and ALBs can accept JWTs for authentication.
- Cannot directly access most AWS resources; that requires temporary AWS credentials.
Amazon Cognito – Identity Pools

- Purpose: provide access to AWS resources by exchanging an identity token for temporary AWS credentials.
- Identity types:
- Unauthenticated identities – guest users with limited access to AWS resources.
- Federated identities – external identity (Google, Facebook, SAML 2.0, or Cognito user pool JWT) swapped for temporary AWS credentials.
- External IDPs handle authentication; your app never sees third-party credentials.
- Identity pools support:
- Social IDPs (Google, Facebook, etc.)
- Cognito user pool JWTs
- Requires configuration for each IDP in the identity pool.
- Credentials are temporary but can be refreshed by Cognito.
- Role assumption: Cognito maps identities to IAM roles and returns temporary credentials.
- Must define roles for both authenticated/federated users and unauthenticated/guest users.
Amazon Cognito – Web Identity Federation (User Pools + Identity Pools)

- Web Identity Federation: process of exchanging a third-party IDP token for AWS credentials.
- User pools consolidate internal and external users.
- Identity pools only need to integrate with the user pool JWT for temporary AWS credentials.
- Reduces the need to configure multiple external IDPs directly in identity pools.
AWS Glue Basics
AWS Glue – Overview
- Serverless ETL (Extract, Transform, Load) and Data Catalog service
- Compared to AWS Data Pipeline:
- Data Pipeline can perform ETL but uses compute servers (creates Amazon EMR clusters).
- Glue is serverless, ad-hoc, and cost-efficient—preferred in exams when a serverless ETL solution is required.
- Compared to AWS Data Pipeline:
- Two primary functions:
- Move and transform data between sources and destinations.
- Crawl data sources and generate data catalogs.
- Fully managed by AWS:
- Serverless, public, and regionally resilient.
- Automatically scales based on workload.
AWS Glue – Data Catalogs
- Data Catalog: centralized repository of metadata with data management and search tools.
- Stores persistent metadata about data sources within a region.
- Regional & account scope:
- One catalog per AWS region per account.
- Avoids data silos and improves visibility of metadata across an account.
- Metadata can be browsed or used in ETL workflows for other services.
- Integration with other AWS services:
- Amazon Athena, Amazon Redshift Spectrum, Amazon EMR, AWS Lake Formation, and more.
- Data crawlers:
- Configured with credentials to access and scan data sources.
- Automatically detect schemas and tables, storing metadata in the catalog.
AWS Glue – Architecture

- Supported data sources:
- Data stores: Amazon S3
- Databases: RDS, Redshift, DynamoDB, or any JDBC-compatible DB
- Streams: Kinesis Data Streams, Apache Kafka
- Supported data targets:
- Data stores: Amazon S3
- Databases: RDS, Redshift, or JDBC-compatible DBs
- Data Catalog access:
- Accessible to Glue jobs and other systems, e.g., via AWS Management Console.
- Makes metadata visible and reusable across the organization.
- Glue Jobs (ETL Jobs):
- Serverless execution—no need to manage compute resources.
- AWS allocates resources from a warm pool; billing is based only on used resources.
- Jobs can be triggered manually or automatically by events.
- Serverless execution—no need to manage compute resources.
Amazon MQ Basics
Apache ActiveMQ
- Open-source message broker
- Written in Java and widely used in enterprise systems.
- Enables communication between distributed applications, regardless of language or hosting environment.
- Supports standard APIs and protocols such as JMS, AMQP, MQTT, OpenWire, and STOMP.
- Provides both queues (point-to-point) and topics (publish-subscribe) messaging models.
- Comparison with Amazon SQS and SNS:
- SQS and SNS provide similar messaging capabilities but are AWS-native services.
- They use AWS-specific APIs instead of industry-standard protocols.
- They are fully managed, highly available, and deeply integrated with AWS.
- Migration challenge:
- Applications built on industry-standard messaging systems may not work with SQS/SNS without modification.
- A standards-compliant solution is often required → this is where Amazon MQ is used.
Amazon MQ – Overview
- AWS-managed service for Apache ActiveMQ
- Provides managed message brokers that support industry-standard APIs and protocols.
- Deployment options:
- Single instance
- Lower cost, single Availability Zone resilience.
- Suitable for development and testing.
- High availability (HA) pair (active/standby)
- Multi-AZ deployment for production workloads.
- Single instance
- Networking model:
- Not a public service.
- Runs inside a VPC and requires private networking.
- Integration considerations:
- Does not offer native integrations with most AWS services.
- Requires managing compatibility with Apache ActiveMQ standards.
- AWS services are generally designed to integrate with SQS and SNS instead.
Amazon MQ – HA Architecture

- Active/standby brokers deployed across two Availability Zones
- Shared storage is provided using Amazon EFS.
- Hybrid connectivity:
- Supports private connections to on-premises ActiveMQ brokers.
- Can use Site-to-Site VPN or Direct Connect.
- Application integration:
- Applications running on EC2 within the VPC can communicate using standard protocols.
- No immediate application changes are required during migration.
- Supports hybrid and phased migration architectures
Amazon MQ vs SQS and SNS – Exam Considerations
- Default choice:
- Use SQS and SNS for most new AWS-based messaging solutions.
- Better integration with AWS services (IAM, monitoring, encryption, etc.).
- Use SQS and SNS for most new AWS-based messaging solutions.
- Use Amazon MQ when:
- Migrating existing systems that rely on industry-standard messaging with minimal code changes.
- Applications require JMS or protocols such as AMQP, MQTT, OpenWire, or STOMP.
- Important requirement:
- Amazon MQ requires proper VPC and private network configuration.
Amazon AppFlow Basics
Amazon AppFlow – Overview
- App integration service
- Functions like middleware for connecting applications.
- Enables data exchange between connectors using configurable flows.
- Flow: primary unit of configuration
- Combines source connector + destination connector + optional components such as transformations or filters.
- Fully managed by AWS:
- Serverless, auto-scaling, and regionally resilient.
- Public service with public endpoints, enabling integration with SaaS apps like Slack, Zendesk, and Salesforce.
- Can also work with AWS PrivateLink for VPC-private integration.
- Connectors:
- Supports many popular SaaS apps.
- Custom connectors can be developed using the AppFlow Custom Connector SDK.
- Common use cases:
- Data synchronization across apps
- Example: sync support tickets from Slack or Zendesk into Amazon Redshift for analysis.
- Data aggregation across sources to reduce silos
- Example: copy Salesforce contact records into S3 for centralized storage.
- Data synchronization across apps
Amazon AppFlow – Architecture

- Connections: store configuration and credentials to access applications.
- Defined separately from flows, allowing reuse across multiple flows.
- Flows: define main processing logic
- Source and destination mappings (which connections to use).
- Optional data transformations.
- Optional filtering and validation of data.