High Availability (HA) and Scaling
AWS Regional and Global Architecture
Global vs Regional Applications
- Global applications (e.g., Netflix) are composed of multiple independent regional applications, each duplicated in different AWS regions.
- This approach simplifies scaling and managing large platforms.
- Three common AWS system architectures:
- Single-region systems – all infrastructure resides in one region
- Single-region systems with disaster recovery – secondary/failover region exists
- Multi-region systems – designed to remain operational even if one or more regions fail
- AWS services are mostly regional, with a few global services. All regions together form the AWS Global Infrastructure.
Architectural Components of Cloud Systems
Global Components
- Global Service Location & Discovery
- Determines how users locate the application (e.g.,
netflix.com) - Example: DNS configuration in Amazon Route 53
- Determines how users locate the application (e.g.,
- Content Delivery & Optimization
- Ensures application content is delivered efficiently to users worldwide
- Can use globally distributed storage or rely on a central origin
- Example: Amazon CloudFront caches content closer to users
- Global Health Checks & Failover
- Monitors infrastructure health across regions
- Automatically redirects users to healthy regions during failures
- Example: Route 53 health checks
- Example: Netflix architecture with primary region in the US and secondary in Australia
- Global Architecture Example

Regional Components
- Regional Entry Point
- Defines how users access regional infrastructure
- Example: VPC endpoints, ALBs, API Gateway
- Scaling & Resilience
- Maintains performance under regional load fluctuations or failures
- Example: Auto Scaling Groups (ASGs), ALBs
- Application Services & Components
- Implements core functionality for the region
- Example: EC2 instances, S3 buckets
Regional Application Tiers
- Tiers = logical groupings of application functionality
- Regional Application Tiers

- Web Tier
- Entry point for regional applications
- Abstracts users from underlying infrastructure
- Example: ALB, API Gateway
- Compute Tier
- Provides application logic and processing
- Example: EC2, Lambda, ECS
- Storage Tier
- Supports compute services with data storage
- Example: S3, EBS, EFS
- CloudFront can use S3 as an origin for media
- Database Tier
- Stores structured data for compute tier
- Example: RDS, Aurora, DynamoDB, Redshift
- Caching Tier
- Reduces read load on databases by caching data in memory
- Example: ElastiCache, DynamoDB Accelerator (DAX)
- Application Services
- Additional AWS services enhancing the application
- Examples:
- Simple services: notifications, email (SNS, SES)
- Architecture-changing services: decoupling components (SQS, Kinesis, Step Functions)
EC2 Launch Configurations (LCs) and Launch Templates (LTs)
EC2 Launch Configuration (LC)
- Definition: A pre-defined configuration template for EC2 instances.
- Specifies AMI, instance type, storage, SSH key pair, networking & security groups, user data, IAM role, etc.
- Important: Once created, a launch configuration cannot be modified. Any changes require creating a new LC.
- Use case:
- Used exclusively by Auto Scaling Groups (ASGs) to launch instances with the specified configuration.
- Cannot launch standalone EC2 instances outside of an ASG.
EC2 Launch Template (LT)

- Definition: An advanced version of launch configurations, offering more flexibility and features.
- AWS recommends using LTs over LCs.
- Key features:
- Versioning:
- Multiple versions of a single LT can exist.
- Each version is immutable.
- Standalone instance launch:
- Can launch EC2 instances directly from the EC2 console or CLI, independent of ASGs.
- Extended EC2 feature support:
- Placement groups, capacity reservations, and unlimited mode for burstable instances (T2/T3).
- Versioning:
- Use case:
- ASGs can reference an LT or LC to know the configuration for scaling out.
EC2 Auto Scaling Groups (ASG)
EC2 Auto Scaling Group (ASG) – Key Concepts

- Definition: A logical collection of EC2 instances.
- Provides automatic horizontal scaling and self-healing capabilities.
- Commonly used with Launch Configurations (LCs) or Launch Templates (LTs) and Elastic Load Balancers (ELBs) to build elastic and resilient architectures.
- Instance provisioning:
- ASGs rely on an associated LC or LT to define how instances are launched during scaling events.
- At any time, an ASG is linked to only one LC or LT.
- This association can be updated, but only one configuration is active at a time.
- All instances launched follow the currently attached LC/LT.
- Conceptual distinction:
- ASG defines when and where instances run
- LC/LT defines what instances look like
EC2 ASG – X:Y:Z Model
- ASG capacity is defined using three values:
- Minimum (MIN) – the lowest number of instances allowed
- Desired Capacity – the target number of running instances
- Maximum (MAX) – the upper limit of instances
- Example:
1:2:4- MIN = 1, DESIRED = 2, MAX = 4
- Core behavior:
- The ASG continuously ensures the number of running instances matches the desired capacity.
- If below desired → launches new instances
- If above desired → terminates instances
- The ASG continuously ensures the number of running instances matches the desired capacity.
- Adjusting desired capacity:
- Manually: user updates desired value directly
- Automatically: scaling policies adjust capacity based on metrics (e.g., CPU usage)
- Desired capacity is always kept within the MIN–MAX range
EC2 ASG – Architecture

- VPC integration:
- ASGs operate within a VPC and can span multiple subnets and Availability Zones (AZs)
- Instances are launched across configured subnets
- By default, ASG tries to distribute instances evenly across AZs
- Health checks:
- Default: EC2 status checks
- Optional: integrate with ELB/ALB health checks
- If an instance is unhealthy, ASG replaces it automatically (self-healing)
- Simple high availability pattern:
- Use a Launch Template
- Configure multiple subnets across AZs
- Set ASG to
1:1:1 - Result:
- Instance is automatically replaced if it fails
- Can recover in another AZ if needed
- Provides a low-cost HA setup for a single instance
EC2 ASG – Scaling Processes
- ASG includes configurable processes that control scaling behavior
- These processes can be suspended (disabled) or resumed (enabled)
- Key processes:
- Launch: controls instance creation
- Terminate: controls instance removal
- AddToLoadBalancer: registers instances with an ELB
- AlarmNotification: enables response to CloudWatch alarms
- AZRebalance: maintains even distribution across AZs
- HealthCheck: performs health monitoring
- ReplaceUnhealthy: replaces failed instances
- ScheduledActions: enables time-based scaling
- Standby: allows instances to be temporarily removed from service
- Useful for maintenance without termination
EC2 ASG – Additional Features
- Scaling granularity:
- Using smaller instance types allows more precise scaling adjustments
- Integration with load balancing:
- Automatically registers/deregisters instances with ELB target groups
- Provides abstraction between users and infrastructure
- Enables dynamic and elastic scaling
- Cost model:
- ASGs themselves are free of charge
- Costs come from the underlying resources (EC2, etc.)
- Use cooldown periods to prevent excessive scaling and unnecessary costs
EC2 Auto Scaling and ASG Scaling Policies
EC2 Auto Scaling – Types
- Manual Scaling
- Adjust ASG capacity values directly without a scaling policy.
- MIN, DESIRED, MAX values are static but can be modified manually via AWS Console, CLI, or custom scripts.
- Customer controls scaling logic and execution.
- Use cases: testing ASGs, cost management, or urgent capacity changes.
- Scheduled Scaling
- Automatically updates DESIRED capacity at specified times.
- Does not require a scaling policy.
- Implemented using scheduled actions in the ASG.
- MIN and MAX values remain unchanged and must be modified separately.
- Useful for predictable traffic patterns, e.g., peak business hours or promotional events.
- Dynamic Scaling
- Automatically adjusts DESIRED capacity based on real-time metrics or CloudWatch alarms.
- Requires a scaling policy attached to the ASG.
- Only DESIRED capacity is updated automatically; MIN and MAX still need manual configuration.
- Dynamic scaling types:
- Simple Scaling – single-step scale out/in actions
- Step/Stepped Scaling – multi-step scaling based on metric thresholds
- Target Tracking – ASG maintains a metric near a defined target
ASG Scaling Policies (Dynamic Scaling)
- Purpose: Define rules that automatically adjust ASG capacity in response to metric changes or CloudWatch alarms.
- Metrics:
- Internal (EC2-based): CPU, memory, disk I/O, etc.
- Some require the CloudWatch Agent to be installed.
- External (outside EC2): e.g., SQS queue length.
- Example: scale an EC2 worker pool based on
ApproximateNumberOfMessagesVisiblein SQS to speed up processing when the queue grows.
- Example: scale an EC2 worker pool based on
- Internal (EC2-based): CPU, memory, disk I/O, etc.
- Cooling Period:
- Time interval (seconds) after a scaling action before the next action can occur.
- Prevents rapid, repetitive scaling and helps reduce costs, since EC2 instances have minimum billing increments.
EC2 ASG – Simple Scaling

- Typically uses one rule for scale out and one for scale in, guided by a CloudWatch alarm.
- Example: Average CPU utilization for the ASG:
- Scale Out: CPU > 50% → +2 instances
- Scale In: CPU < 50% → -2 instances
- Limitation: Inflexible. The number of instances added/removed is fixed regardless of how far metrics exceed thresholds.
EC2 ASG – Step/Stepped Scaling

- Builds on Simple Scaling with multiple rules and steps for different thresholds.
- Example: CPU-based rules:
- Scale Out:
- 50–59% → 0 instances
- 60–69% → +1 instance
- 70–79% → +2 instances
- 80–100% → +3 instances
- Scale In: parallel rules with proportional decrements.
- Scale Out:
- Advantages:
- Reacts more accurately to changing workloads.
- Handles variable load efficiently.
- Preferred over Simple Scaling for most real-world scenarios.
EC2 ASG – Target Tracking
- ASG attempts to maintain a metric near a defined target value automatically.
- Example: Desired average CPU = 40% → ASG adds or removes instances to stay close to 40%.
- Not all metrics are supported.
- Supported example:
ALBRequestCountPerTarget– average number of requests per target behind an Application Load Balancer for your ASG.
- Supported example:
- Ideal for maintaining steady performance without manual intervention.
Auto Scaling Group (ASG) Lifecycle Hooks
EC2 ASG – Lifecycle Hooks

- Default ASG behavior for instance state transitions:
- Launch: EC2 instance moves from
Pending→InServiceautomatically. - Termination: EC2 instance moves from
Terminating→Terminatedautomatically. - Without lifecycle hooks, ASG carries out these transitions immediately, leaving no opportunity to intervene.
- Launch: EC2 instance moves from
- Purpose of lifecycle hooks:
- Allow custom actions during instance launch or termination.
- Pause the instance at a transition state so you can perform tasks before the ASG continues.
- How lifecycle hooks work:
- Instances are temporarily paused during launch/termination.
- The ASG resumes the transition when either:
- Timeout expires – default 3600 seconds (1 hour). ASG can then either continue or abandon the action.
CompleteLifecycleActionis executed – signals that the custom action is complete.- Can be invoked via AWS CLI (
complete-lifecycle-action) or programmatically.
- Can be invoked via AWS CLI (
- Example use cases for custom actions:
- Initialize or load data before marking a new instance
InService. - Backup logs, clean up resources, or perform maintenance before terminating an instance.
- Initialize or load data before marking a new instance
- Integration with other AWS services:
- Works with Amazon EventBridge and SNS notifications for event-driven workflows triggered by instance launch or termination.
AWS Elastic Load Balancer (ELB)
Traditional Load Balancer (LB)
- A server that receives client connections and distributes them evenly across multiple backend resources.
- Clients do not interact directly with backend servers.
- Backend resources can fail or scale without affecting the client experience.
AWS Elastic Load Balancer (ELB) – Architecture

- ELB = fully managed load balancer within your VPC.
- Nodes deployed in at least 2 AZs → ensures high availability and scalability.
- Backend resources are registered in a Target Group (TG):
- Can include EC2 instances, EC2 Auto Scaling Groups, Lambda functions, etc.
- Elastic emphasizes AWS cloud’s ability to scale automatically.
- Historical note: ELB started with only EC2 instances as targets; now it supports multiple resource types.
Configuration highlights:
- IP addressing: IPv4-only or dual-stack (IPv4 + IPv6).
- DNS records resolve to ELB nodes; client connections are distributed across nodes.
- AZ selection: at least one subnet per AZ, minimum 2 AZs.
- Nodes are automatically replaced if they fail and can scale with load.
- Internet-facing vs internal ELB:
- Internet-facing → nodes have public + private IPs.
- Internal → nodes have private IPs only, used for internal tier separation.
- Listeners: define what traffic ELB accepts and how it forwards it to targets.
- ❗ Backend resources can reside in different subnets or be private, regardless of whether the ELB is public or internal.
Subnet requirements for ELB scaling:
- Needs 8+ free IPs per subnet; AWS recommends /27 or larger subnets.
- Technically, a /28 subnet can work (16 IPs minus 5 reserved = 11 usable), but /27 is safer for exam purposes.
ELB – Abstraction of Infrastructure

- Without ELB: clients connect directly to servers → tight coupling between tiers.
- Failures or scaling events disrupt client experience.
- With ELB: clients are abstracted from the backend → loose coupling.
- Servers can fail or scale, clients remain unaffected.
ELB – Cross-Zone Load Balancing

- Traditionally, each LB node only distributed traffic to targets in its own AZ.
- Could cause uneven load if AZs had different numbers of instances.
- Cross-zone balancing: each node can distribute traffic evenly across all registered targets, regardless of AZ.
- Enabled by default in Application Load Balancers (ALBs).
- Important for exams: know that cross-zone load balancing solves uneven distribution issues in multi-AZ setups.
ELB Types – Classic, Application, and Network Load Balancers
AWS Elastic Load Balancer (ELB) – Overview and Types
- v1 (Legacy) – Classic Load Balancer (CLB)
- Considered outdated; migrate to ELB v2 if still in use.
- v2 (Current) – Modern Load Balancers
- Application Load Balancer (ALB) – operates at Layer 7, supports HTTP(S) and WebSockets.
- Network Load Balancer (NLB) – operates at Layer 4, supports TCP, TLS, and UDP.
Note: A fourth type, Gateway Load Balancer (GWLB), exists for specific network appliance use cases and is handled separately.
ELBv1 – Classic Load Balancer (CLB)

- Introduced in 2009; intended for basic load balancing of HTTP(S) and other low-level protocols.
- Connects directly to a single pool of backend instances or ASGs; distributes traffic evenly.
Drawbacks:
- No SNI support → limited to one SSL certificate per CLB → scaling for multiple domains becomes expensive.
- Does not support target groups; can only manage a single backend pool.
- Single-protocol listeners only; cannot combine multiple protocols.
- Cannot perform HTTP-level routing decisions (no path-based or host-based routing, no per-rule health checks).
ELBv2 – Modern Load Balancer

- Released in 2016 with two main types:
- Application Load Balancer (ALB) – Layer 7: HTTP(S), WebSockets
- Network Load Balancer (NLB) – Layer 4: TCP, TLS, UDP
Advantages over CLB:
- Faster performance, lower cost, and supports target groups.
- ALBs allow multiple rules → 1 SSL certificate per rule → host multiple domains and apps on a single ALB.
Application Load Balancer (ALB)

- True Layer 7 load balancer; interprets HTTP(S) protocol and can make routing decisions based on content.
- Supports WebSockets over existing HTTP(S) listeners.
Listener Rules:
- Determine how requests are handled; rules processed in priority order.
- Default rule acts as a fallback.
- Can match conditions such as
host-header,http-header,path-pattern,query-string,source-ip,http-request-method. - Actions can include:
forward,redirect,fixed-response,authenticate-oidc,authenticate-cognito.
Benefits:
- Routes traffic based on HTTP content, cookies, headers, user IP, and application behavior.
- Supports Layer 7 health checks to evaluate application-level availability.
- Handles multiple SSL certificates per rule (SNI support) → consolidate multiple apps/domains on one ALB.
Limitations:
- Cannot handle non-HTTP(S) protocols (SMTP, SSH, gaming).
- Cannot use Layer 4 listeners; no support for static EIPs.
- Higher processing overhead → slightly slower than NLBs.
- HTTPS connections are terminated at the ALB → backend receives a new connection; SSL termination must be configured.
Network Load Balancer (NLB)
- Layer 4 load balancer → supports TCP, TLS, UDP, and TCP_UDP listeners.
- Extremely high throughput → handles millions of requests per second with very low latency (~25% of ALB latency).
- Can use static public IPs (EIPs) → useful for firewall whitelisting.
- Supports TCP pass-through → end-to-end SSL encryption preserved.
Limitations:
- Cannot inspect HTTP(S) content → no content-based routing, cookies, or session stickiness.
- Health checks only at network level (ICMP/TCP), not application-aware.
- No native support for multiple SSL certificates (SNI).
Use Cases:
- Applications that do not use HTTP(S) → SMTP, SSH, gaming, or custom TCP/TLS protocols.
- Services exposed privately via AWS PrivateLink.
- High-performance, low-latency applications requiring static IPs.
Choosing Between ALB and NLB
- Default choice: ALB for typical web applications requiring Layer 7 routing.
- Choose NLB when you need:
- End-to-end SSL encryption between client and backend
- Static IP (EIP) for whitelisting
- Ultra-high performance (millions of requests/sec, low latency)
- Non-HTTP(S) Layer 7 protocols (e.g., SMTP, SSH, gaming)
- PrivateLink services for secure VPC access
In all other cases, ALB provides greater flexibility with Layer 7 features.
ELB – SSL Termination
AWS ELB – Approaches for Handling SSL

- ELBs can manage HTTPS traffic using three main paradigms, each with advantages and trade-offs:
- SSL Bridging – default behavior for ALBs
- SSL Pass-through – typical for NLBs
- SSL Offload – optional configuration for ALBs
ALB – SSL Bridging
- Uses two separate SSL connections: client ↔ ALB and ALB ↔ backend.
- SSL is terminated at the ALB, then re-encrypted toward the backend.
- Default for HTTPS listeners on ALBs.
Key Points:
- ALB requires an SSL certificate and handles encryption/decryption.
- Allows Layer 7 awareness, so routing and actions based on HTTP(S) traffic are possible.
- AWS has access to the SSL certificate, which may not meet strict security policies.
- Backend instances also need SSL certificates and perform their own crypto operations.
- Ensures end-to-end encryption, increasing overall security.
- Compute overhead on instances → higher latency and cost under heavy traffic.
- Managing SSL certificates on multiple instances adds administrative overhead.
NLB – SSL Pass-through
- Establishes a single uninterrupted SSL connection from client to backend.
- NLB forwards traffic directly to targets without decrypting it.
- Uses TCP listeners; no SSL termination at the NLB.
Key Points:
- NLB does not require an SSL certificate.
- No Layer 7 awareness → cannot inspect or route based on HTTP(S) content.
- AWS does not see your SSL certificate → better for environments with strict security requirements.
- Certificates can be managed externally (e.g., CloudHSM) for additional security.
- Backend instances must handle SSL themselves.
- Ensures fully encrypted communication.
- Compute overhead and administrative effort are similar to SSL Bridging.
ALB – SSL Offload
- Uses encrypted connection between client and ALB, but plaintext from ALB to backend.
- Data is secure over the internet but unencrypted within AWS network.
- Requires an HTTPS listener, but this is not the default ALB behavior.
Key Points:
- ALB requires an SSL certificate for the client connection and handles encryption/decryption.
- Layer 7 awareness maintained → can take actions based on HTTP(S) traffic.
- AWS has access to the certificate, so may not fit high-security environments.
- Backend instances do not need SSL certificates; traffic is unencrypted.
- Reduces instance CPU usage → lower latency and cost at scale.
- Simplifies administration → no certificate management per instance.
- Least secure option if AWS network security is a concern.
SSL Handling in ELB – Overview Table
| SSL Approach | Load Balancer Type | Listener Protocol | Certificate on ELB | Certificate on EC2 Instances |
|---|---|---|---|---|
| SSL Bridging | Application Load Balancer (ALB) | HTTPS | Present | Present |
| SSL Pass-through | Network Load Balancer (NLB) | TCP | Not used | Required |
| SSL Termination (Offload) | Application Load Balancer (ALB) | HTTPS | Present | Not required |
ELB – Session Affinity (Stickiness)
ELB Session/Connection Stickiness – Overview
- By default, ELB connections are not sticky. Traffic is distributed evenly across all backend instances.
- The ELB does not remember which instance a client previously connected to.
- Works fine for stateless applications or when user sessions are stored externally (e.g., ElastiCache, DynamoDB).
- Can cause issues for server-side session storage → client may lose session if routed to a different instance.
- The ELB does not remember which instance a client previously connected to.
- Session stickiness ensures a client connects to the same backend instance for a defined period or until that instance fails.
- Enabled at the ELB Target Group (TG) level.
- Useful when applications rely on stateful server-side sessions.
- Trade-offs:
- Uneven backend load is possible → high-traffic clients may overload a single instance while others remain underutilized.
- Best practice: design applications to be stateless whenever possible.
ALB Session Stickiness

AWSALBcookie binds a client to a specific instance for a configurable time (1 second to 7 days).- How it works:
- Cookie is generated on the first client connection to the ALB.
- Subsequent requests include the
AWSALBcookie, instructing the ALB which backend instance to use.
- Client remains connected to the same instance until:
- The cookie expires, or
- The backend instance fails.
NLB Session Stickiness
- Stickiness is based on client source IP (SRC IP affinity).
- Requests from the same client IP are routed consistently to the same backend instance.
- Can set a stickiness duration; after that, the client may be routed to a different instance.
- No cookies required → NLB does not generate or use cookies.
- NLB does not inspect HTTP headers, so no
AWSNLBcookie exists.
- NLB does not inspect HTTP headers, so no
Demo – ALB Session Stickiness
- Default behavior: connecting to the ALB DNS endpoint routes you to a backend instance using round-robin.
- Enabling stickiness:
- Go to Target Groups → select your target group → Attributes → Edit.
- Enable session stickiness and configure duration.

- Behavior after enabling:
- The client connection is locked to a specific instance via the
AWSALBcookie. - If the locked instance fails or is stopped, the client is routed to a new instance and the cookie updates.
- Restarting the original instance does not revert the client back; the stickiness follows the new instance.
- The client connection is locked to a specific instance via the
ASG – ELB Integration and Health Checks
ASG-ELB Integration

- EC2 Auto Scaling Groups (ASGs) can be registered with an ELB Target Group (TG).
- Instances launched or terminated by the ASG are automatically added or removed from the TG.
- Benefits of combining ASGs with ELBs:
- ELB abstracts infrastructure → client traffic continues uninterrupted even if instances scale or fail.
- ASG provides dynamic scaling and elasticity → automatically adjusts compute capacity.
- App-aware scaling → ASG can use ELB health checks alongside EC2 instance status checks to determine instance health.
ASG Health Checks
- Purpose: ASGs use health checks to monitor instance status and automatically replace unhealthy instances.
- Types of health checks:
- EC2 instance status checks (default)
- An instance is considered healthy only if it is in the
Runningstate AND passes both 2/2 status checks. - Instances in states like
Stopping,Stopped,Shutting Down, orTerminatedor failing checks are marked unhealthy.
- An instance is considered healthy only if it is in the
- ELB health checks (optional, when ASG is attached to ELB)
- An instance is healthy only if both ELB checks and EC2 status checks pass.
- Provides network-level (L4) or application-level (L7) health monitoring (L7 only with ALB).
- Misconfiguration can cause problems:
- Example: ELB checks a simple HTML page, but the app’s backend (e.g., database) is failing → ASG may continuously replace instances unnecessarily.
- Custom health checks
- Any external system can mark instances as healthy/unhealthy.
- Allows ASGs to meet specific business requirements or integrate with monitoring tools.
- Health Check Grace Period
- Delay before ASG begins monitoring instance health after launch.
- Default = 300 seconds (5 minutes).
- Ensures instances have time to start up and initialize applications before health checks begin.
- A too-short grace period can trigger continuous provisioning and termination loops, as instances fail checks before they are fully ready.
Gateway Load Balancer (GWLB) – Traffic Management for Network Appliances
Scaling Challenges with Network Security Appliances

- Some applications require inspection-based network security to prevent sensitive data leaks or detect malicious activity.
- This often involves deploying a virtual security appliance in a dedicated subnet that inspects all traffic entering or leaving a VPC.
- Malicious or unwanted traffic can be blocked, improving overall security posture.
- Problem: traditional inline security appliances do not scale efficiently.
- App instances that scale dynamically require security appliances to scale proportionally, creating tight coupling between app and security layers.
- This approach becomes complex and inefficient, especially for multi-application environments.
AWS Gateway Load Balancer (GWLB) – Core Concepts

- GWLB enables load balancing of traffic to virtual appliances in separate VPCs.
- Provides transparent, inline security while allowing appliances to scale independently.
- Supports deployment and management of third-party virtual appliances such as firewalls, intrusion detection systems, or data inspection tools.
- Functionality:
- Works like a Layer 3/4 load balancer (similar to NLB) but encapsulates traffic to backend appliances using the GENEVE protocol.
- Main advantage: horizontal scaling of security appliances without changing app or client traffic flow.
- Two key components:
- GWLB Endpoint (GWLBE)
- Resides in a VPC and acts as the ingress/egress point for traffic.
- Can be used as the next hop in route tables, integrating with VPC traffic flows.
- Conceptually similar to standard VPC endpoints but with enhanced capabilities.
- GWLB (Load Balancer itself)
- Distributes traffic across multiple backend virtual appliances (EC2 instances running security software).
- GWLB Endpoint (GWLBE)
- Configuration: GWLBs are managed at the VPC level, not within the EC2 console, even though they are technically a type of ELB.
GENEVE Protocol in GWLB
- GENEVE encapsulates traffic for inspection within the security VPC.
- Ensures original source and destination IPs remain intact, so traffic can return correctly to the originating VPC.
- Traffic is tunneled to security appliances with temporary addresses, and encapsulation is removed when returning to the customer VPC.
- Flow stickiness:
- Each flow is consistently sent to the same appliance, allowing stateful inspection.
- Traffic inspection is transparent to applications and clients, maintaining seamless connectivity.
Example GWLB Architecture and Traffic Flow

- Traffic enters the IGW, destined for an ALB with a public IP in subnet
10.16.9.0/20. - IGW updates the destination IP to the ALB’s private IP and forwards traffic to GWLBE2.
- GWLBE2 sends packets to the GWLB in the
securityVPC. - GWLB encapsulates traffic using GENEVE, preserving original source/destination IPs, and forwards to a selected security appliance.
- Security appliance inspects traffic and either blocks or returns it.
- Packets are returned to GWLB with GENEVE encapsulation removed.
- Traffic passes back through GWLBE2 to the application VPC (
catagramVPC). - Local routing directs traffic from GWLBE2 to the ALB.
- ALB distributes traffic to the appropriate application instance.
- The return path follows the same logic, maintaining traffic integrity and inspection throughout.
Serverless and Application Services
Architecture Deep Dive Concepts
CatTube (Example App)
- Reference application: CatTube, a video-sharing platform focused on cat content, where users upload and stream videos
- Core components:
- Users upload videos
- Uploaded content is processed into multiple formats and resolutions
- This is the most compute-intensive part of the system
- The platform serves videos and handles playlists, channels, and user interactions
- Requires reading from and writing to databases
- This same application is used to illustrate different architectural patterns
- Notes marked with relate specifically to the CatTube example
Monolithic Architecture

- A single application unit (one server or system) that contains all components
- Even if logically separated in code, everything runs together on the same machine
- Represents a traditional design approach
- Advantages:
- Simple to build and understand
- Disadvantages:
- Tight coupling between components
- Failures in one part can impact the entire system
- If the upload feature breaks, processing and storage may also be affected
- Scaling is uniform
- Typically requires vertical scaling
- Cost inefficiency
- All parts run continuously, even when not needed
- Processing resources remain active even when no uploads occur
- Tight coupling between components
- Monolithic systems are generally inefficient at scale and can lead to higher operational costs
Tiered Architecture

- Application is divided into separate layers (tiers)
- Each component runs in its own tier (same or different servers)
- Example: UPLOAD, PROCESSING, and STORAGE are isolated tiers
- Advantages:
- Independent scaling per tier (vertical or horizontal)
- Adding internal load balancers can:
- Improve availability
- Enable horizontal scaling
- Reduce direct dependency on infrastructure
- Processing tier can scale without affecting upload or storage tiers
- Disadvantages:
- Still tightly coupled due to synchronous communication
- Each tier depends on immediate responses from others
- Always-on requirement
- Each tier must remain active for the system to function
- Upload depends on processing being available
- No scale-to-zero capability
- Processing must run even when idle
- Failure propagation
- If processing fails or slows, uploads are impacted
- Still tightly coupled due to synchronous communication
Asynchronous Queues Architecture
- Introduces queues to enable asynchronous communication
- Messages are sent to and retrieved from a queue
- Ordering may follow FIFO or other models
- Key idea:
- Decouple tiers using queues instead of direct communication
- Advantages:
- Loose coupling between components
- Services interact with queues instead of each other
- Independent scaling
- Components can scale from zero to very high capacity
- Loose coupling between components
- CatTube workflow:
- UPLOAD
- Stores video in S3
- Sends a message to a queue
- Upload process completes immediately without waiting
- PROCESSING
- Worker instances pull tasks from the queue
- ASG can scale dynamically (including MIN=0)
- Instances launch only when jobs exist and terminate when done
- Reduces idle cost
- Same pattern applies between processing and storage layers
- UPLOAD


Microservices Architecture

- System is split into many small, independent services
- Each service focuses on a specific function
- A microservice is:
- A self-contained application that performs a single responsibility well
- Types:
- Producer → generates data/events (e.g. upload service)
- Consumer → processes data/events (e.g. processing service)
- Hybrid → does both (e.g. storage/management service)
- Communication:
- Often uses queues or events
- Large systems may require many queues, increasing complexity
- Event-driven approaches help simplify this
Event-Driven Architecture (EDA)

- Built around event producers and consumers
- Producer: generates events when something happens (e.g. upload, click)
- Consumer: reacts to those events (e.g. process video, log activity)
- Some components act as both
- Key characteristics:
- No constant running or polling
- Resources are only used when handling events
- System automatically scales up and down based on activity
- Benefits:
- Efficient resource usage
- High scalability and responsiveness
- Event Router:
- Central system that distributes events to consumers
- Contains an event bus for continuous event flow
- Ensures proper routing of events
- Example: Amazon EventBridge
- Many serverless systems follow this model, where compute runs only when triggered by events
AWS Lambda Basics
AWS Lambda – Key Concepts
- Function-as-a-Service (FaaS) model designed for short-lived, single-purpose code execution
- A Lambda function is the code unit executed by the service
- It represents the main configuration entity in AWS Lambda
- Informally, “a Lambda” usually refers to a Lambda function
- A Lambda function is the code unit executed by the service
- Before running, a function must define a Runtime Environment (RTE) (e.g. Python 3.8)
- Memory is explicitly configured, while vCPU allocation scales indirectly based on that memory
- When invoked, the function is loaded into the selected runtime and executed
- Billing is based only on execution time and resources used
- Core component of serverless and event-driven architectures
- Typically low cost, with a free tier covering initial usage and low per-invocation pricing beyond that
AWS Lambda – Architecture

- A Lambda function consists of code, configuration, and supporting components
- Requires:
- A defined programming language/runtime
- A deployment package (downloaded and executed at runtime)
- Configured resource settings
- Although often referred to as just code, it includes more—similar to how an AMI includes more than just a VM image
- Requires:
- Supports multiple runtimes such as Python, Node.js, Java, and others
- Lambda Layers allow extending functionality or even enabling custom runtimes
- Selecting a runtime determines the available libraries and environment setup
- Each invocation typically results in a new runtime instance being created
- Code is loaded, executed, and then the environment is terminated
- Future executions usually start fresh, though reuse can occur in some cases
- Stateless execution model
- No guaranteed persistence between runs
- Code must function correctly without relying on previous executions
- Docker note:
- Traditional container usage is not the same as Lambda execution
- While Lambda supports container images, they are specifically built for Lambda’s environment
- Standard container-based compute (e.g. ECS) should not be confused with Lambda
Resource Configuration
- Memory: 128 MB to 10,240 MB (configurable in 1 MB increments)
- vCPU: Scales proportionally with memory (approximately 1 vCPU per 1769 MB)
- Temporary storage:
- Default 512 MB (expandable to 10,240 MB)
- Mounted at
/tmpand should be treated as ephemeral
- Maximum execution time: 900 seconds (15 minutes)
- Longer workflows require orchestration tools such as Step Functions
- Execution role:
- IAM role assumed by the function
- Controls permissions and access to AWS services
AWS Lambda – Common Use Cases
- Serverless application backends (e.g. API Gateway + Lambda)
- File processing pipelines
- Example: processing or transforming files uploaded to S3
- Database-triggered processing
- Reacting to changes in DynamoDB via streams
- Scheduled automation (serverless cron jobs)
- Triggered by EventBridge or CloudWatch Events
- Real-time stream processing
- Handling incoming data from services like Kinesis
Demo: Creating and Running a Lambda Function
- Deploy a CloudFormation stack to provision required resources (e.g. EC2 instances)
- Create an execution role with permissions (e.g. logging and EC2 control actions)
- Navigate to Lambda and create a new function
- Assign a name and choose a runtime (e.g. Python 3.9)
- Attach the execution role
- Add function code
- Example: script to stop EC2 instances using environment variables


5. Configure environment variables
- Example:
EC2_INSTANCEScontaining instance IDs
6. Run a test invocation
- Verify output in logs and confirm changes in EC2 console
7. Optionally create another function (e.g. to start instances) and test similarly
8. Perform cleanup by deleting Lambda functions and the CloudFormation stack

9. Clean-up: remove the Lambda functions that were created, and then delete the CloudFormation stack to terminate all associated resources.
AWS Lambda Networking
Public Lambda (Default)

- Lambda executes within the AWS public network environment
- Can communicate with publicly accessible AWS services (e.g. SQS, DynamoDB) and the internet
- This is the default configuration and is suitable for most use cases
- A private setup is only needed when specific VPC access is required
- No need to configure a customer VPC
- Advantage: delivers optimal performance since it runs on shared AWS-managed infrastructure
- Limitation: cannot reach private VPC resources unless those resources are exposed externally
- External access requires public IPs and appropriate security configurations
Private Lambda

- Lambda can be configured to run inside a VPC by attaching network interfaces (ENIs)
- Typically placed in private subnets
- Functions operating in a VPC must follow standard VPC networking rules
- Can access internal resources if security groups and NACLs allow it
- Cannot access external services unless additional configuration is in place
- Internet access requires a NAT Gateway and Internet Gateway
- Private access to AWS services can be enabled using VPC Endpoints
- The execution role must include permissions for EC2 networking operations
Private Lambda ENI Injection – Old vs New Approach
Old approach:

- Each function invocation created and attached an ENI inside the VPC
- Drawbacks:
- Increased latency due to ENI creation during execution
- Poor scalability, especially with high concurrency
- Large number of ENIs could impact VPC performance
New approach:

- AWS precomputes combinations of subnets and security groups used by functions
- Creates shared ENIs per unique subnet + security group combination
- Multiple function executions can reuse the same ENIs
- Benefits:
- Much better scalability for concurrent executions
- Eliminates per-invocation ENI creation delays
- There is an initial setup delay (around 90 seconds) when configuring networking
- This happens only once during setup or configuration changes, not during execution
AWS Lambda Security, Monitoring, and Versioning
AWS Lambda – Security

- Lambda execution role
- An IAM role assumed by the Lambda function during execution
- The trust policy allows Lambda to assume the role
- The permissions policy defines what the function is allowed or denied to do
- Example: read data from DynamoDB and write it to S3
- Lambda resource policy
- A resource-based policy attached to the Lambda function
- Determines which principals are allowed to invoke the function
- Can grant access to AWS services (e.g. S3, SNS) or external AWS accounts
AWS Lambda – Monitoring
- Execution logs are stored in CloudWatch Logs
- The Lambda execution role must include permissions to write logs
- If logs are missing, it usually means permissions were not configured correctly
- The Lambda execution role must include permissions to write logs
- Metrics are automatically collected in CloudWatch
- Includes invocation count, errors, retries, and execution duration
- No additional setup required for basic metrics
- Supports AWS X-Ray integration
- Enables distributed tracing across components
- Useful for tracking request flows in serverless applications
AWS Lambda – Versioning and Aliases
- Lambda supports function versioning (e.g. v1, v2, v3)
- Each version includes both code and configuration
- Versions are immutable
- Once published, they cannot be modified
- Each version has a unique ARN
- Aliases act as pointers to specific versions
- Common examples:
DEV,STAGE,PROD - Can be updated to reference different versions over time
- Common examples:
$LATESTis a built-in alias- Always points to the most recently updated version of the function
AWS Lambda Invocation Methods
Lambda – Synchronous Invocation

- Function called directly via CLI or API, sending input and waiting for the response
- Function executes and returns a result or an error
- Client waits for the outcome
- Success or failure is reported in the same request
- Error handling and retries are managed by the caller
- Commonly used when humans invoke functions via API Gateway endpoints in serverless applications
Lambda – Asynchronous Invocation

- Function triggered by an event, no immediate response tracked
- Typical for AWS services invoking Lambda (e.g., S3 event notifications)
- Lambda manages its own errors
- Failed executions can be retried automatically (0–2 times, configurable)
- Functions must be idempotent to handle retries safely
- Idempotent means running multiple times produces the same end result
- Example: updating a bank account balance by explicitly setting it (idempotent) vs. incrementing it blindly (not idempotent)
- Event destinations can be configured for success or failure
- Failed events may go to Dead-Letter Queues (DLQs) such as SQS or SNS for later investigation
Lambda – Event Source Mapping

- Lambda polls a source (queue or stream) for data and processes it in batches
- Used for sources that don’t automatically generate events (e.g., SQS, Kinesis, DynamoDB streams, MSK)
- Batches of events are sent to Lambda
- Batch size should fit within Lambda’s 15-minute timeout to ensure complete processing
- Execution role permissions required
- Lambda must have read access to the source for polling-based invocations
- Asynchronous event-based invocations typically include all needed information in the event
- Error handling options
- Failed batches can be sent to SQS or SNS for monitoring, retries, or diagnostics
AWS Lambda Execution Environment
AWS Lambda – Cold vs Warm Starts

- Lambda runs inside an execution context (RTE)
- Think of it as a lightweight container with allocated resources for the Lambda code
- Functions must generally be stateless, even if context reuse is possible
- Always assume a new execution context may be created on each invocation
- Cold start = creating a new execution context
- Provision hardware and environment
- Download and initialize runtimes (libraries, interpreters, packages)
- Load deployment package (your code and dependencies)
- Impact: cold starts take extra time (hundreds of milliseconds or more), especially noticeable in synchronous requests
- Warm start = reusing an existing execution context
- Context from a previous invocation may be reused if function is called again shortly after
- No need to reinitialize environment or load packages → faster execution
- Important: never rely on context reuse
- Idle contexts are removed automatically
- Concurrent executions create multiple contexts → parallel executions often result in multiple cold starts
AWS Lambda – Reducing Cold Start Latency
- Provisioned Concurrency
- Pre-creates a fixed number of execution contexts ready to serve requests → reduces cold start delays
- Ideal for:
- Predictable high traffic periods
- Prewarming environments before a production release
- Use
/tmpfor caching- Temporarily store frequently used files or data (e.g., media assets) between invocations
- Functions must still handle clean environments in case
/tmpis empty
- Define reusable components outside the handler
- Code outside the function handler persists in the execution context between invocations
- Example: database connections, heavy library objects
- Ensure fallback logic exists if the context is cold
- Summary: Optimize performance by reusing components when possible, but design Lambda to work correctly on a completely fresh execution context every time.
Amazon EventBridge – Serverless Event Bus Service
Amazon EventBridge – Overview and Architecture

- Purpose: Centralized event management for your AWS account
- Tracks changes in AWS services (e.g., EC2 instance terminated)
- Provides:
- Event visibility via a near-real-time stream (Event Bus)
- Delivery of events to configured targets
- Enables event-driven architectures (EDAs)
- Event Bus: a stream that collects events
- Default Event Bus: automatically available in every AWS account; contains all system events
- Custom event buses can be created to handle events from external sources or other accounts
- Event Routing Pattern: “If X happens, or at Y time(s), send info to Z”
X= event generated by an AWS service (event producer)Y= scheduled times (via cron expressions or EventBridge Scheduler)Z= event target/consumer (e.g., Lambda, SQS, SNS)
- Rules: match events or schedules
- Event Pattern Rule → triggered by specific events
- Schedule Rule → triggered at defined times
- Matched events are sent to one or more targets
- Event Format: JSON
- Contains relevant details for targets to consume (e.g., instance ID, new state, timestamp)
CloudWatch Events (CWEvents)
- EventBridge supersedes CWEvents
- CWEvents was the original service for event handling but now redirects to EventBridge
- Underlying architecture/APIs are the same, but EventBridge adds more capabilities
- CWEvents could only monitor the default event bus
- EventBridge supports custom event buses for third-party or application-generated events
DEMO: Building a Simple Event-Driven Architecture (EDA)
Protect an EC2 Instance if It Gets Stopped
- Create a Lambda function that automatically restarts any EC2 instance that enters the
stoppedstate:

- Create an EventBridge rule to monitor EC2 state changes.
- Event to track:
EC2 Instance State-change Notification. - Generate a JSON sample of the event to see what information is delivered.

5. Fill out the event pattern to match instances entering the Stopped state.
- Optionally, filter by specific instance IDs if you only want certain instances protected.

6. Assign the Lambda function as the target for this EventBridge rule.

7. Test the setup by stopping an instance. The Lambda should automatically restart it after a short period.
8. Check logs in CloudWatch Logs for function execution details:
- Each Lambda function creates a log group
- Each execution creates a log stream

Stop All EC2 Instances at a Specific Time Every Day
- Create a schedule rule in EventBridge
- Use the EventBridge Scheduler for a modern UI and flexible scheduling options.
- Unlike the old method, you can define schedules outside of event buses.
- Traditional “Create Rule” only allowed Unix CRON format and required UTC time.
- Specify the schedule using a Unix CRON expression
- Check the time zone carefully:
- CRON expressions default to UTC
- EventBridge Scheduler UI may display times in your local time zone
- Verify next trigger times to ensure the schedule is correct
- Check the time zone carefully:

- Assign the Lambda function that stops EC2 instances as the target for this scheduled rule.

- Wait for the scheduled time
- The Lambda function will automatically stop the instances at the specified time.
- If the EC2 protection Lambda is still active, any protected instances will automatically restart after being stopped.