AWS Java Interview Guide - MD
AWS Java Interview Guide - MD
Table of Contents
1. Compute Services
2. API Management
3. Database Services
4. Security & Access Control
5. Frontend Deployment
6. CI/CD Pipelines
7. Containerization & Orchestration
8. Monitoring & Observability
9. Architecture Patterns
10. Interview Questions & Answers
Compute Services
EC2 (Elastic Compute Cloud)
What It Is:
Virtual servers (instances) that you can launch and manage
Flexible sizing with on-demand, reserved, and spot pricing models
Full control over OS, application stack, and networking
Key Concepts:
Task Definition: JSON file defining container specs (image, CPU, memory,
environment variables, port mappings)
Task: Running instance of a task definition
Service: Long-running tasks with auto-scaling and load balancing
Cluster: Logical grouping of resources (EC2 instances or Fargate capacity)
ECS vs Fargate:
Cost Lower cost for sustained workloads Higher per-task cost, pay-as-you-go
Common patterns:
1. Spring Boot containerized → Fargate service → ALB → RDS
2. Multi-container microservices (logging, metrics sidecars)
3. Batch jobs scheduled via CloudWatch Events
Interview Focus:
How do you configure health checks in ECS?
What's the difference between task placement strategies?
How would you implement zero-downtime deployments in ECS?
Key Concepts:
Pods: Smallest deployable units (usually one container per pod)
Deployments: Manage replicas and rolling updates
Services: Expose pods internally or externally
ConfigMaps & Secrets: Configuration and sensitive data
Ingress: External HTTP/HTTPS routing
StatefulSets: For stateful applications (databases, caches)
Java on EKS:
Spring Boot microservices with automatic scaling
Service discovery via DNS (e.g., [Link] )
Pod autoscaling based on CPU/memory metrics
Volume mounts for persistent storage (EBS, EFS)
AWS Lambda
What It Is:
Serverless compute: Pay only for execution time
Auto-scales from zero to thousands of concurrent executions
Stateless function execution
Java on Lambda:
Cold starts: Java has slower cold starts than [Link]/Python (1-2 seconds typical)
GraalVM native images: Reduce cold start time (100-200ms)
Quarkus/Micronaut: Optimized frameworks for Lambda
Handler functions: Entry point for Lambda execution
Considerations:
Memory: 128MB-10,240MB (affects CPU allocation)
Timeout: Default 3 seconds, max 15 minutes
Concurrency limits: Default 1,000 concurrent executions per account
Packaging: JAR files typically 50MB+ (larger than other runtimes)
Interview Focus:
How would you design for cold starts with Java Lambda?
When would you choose Lambda vs ECS/EKS for a microservice?
How do you structure a Lambda handler with dependency injection?
What are provisioned concurrency and when would you use it?
API Management
API Gateway
What It Is:
Fully managed API service
Create, publish, maintain, monitor, secure APIs
Multiple endpoint types: REST APIs, HTTP APIs, WebSocket APIs
Key Features:
Request/Response Transformation: Map incoming requests to backend format
Authorization: API keys, Lambda authorizers, JWT validation, Cognito
Rate Limiting & Throttling: Protect backend from overload
CORS: Enable cross-origin requests for frontend apps
Caching: Cache responses to reduce backend calls
Stages: dev, staging, prod with separate configurations
Logging: CloudWatch integration for debugging
Cost Per request + data transfer Per LCU (load balancer capacity unit)
Typical Flow:
Angular/React Frontend → API Gateway → Lambda/ECS/EC2 Backend
↓
Authorization check
Request validation
Rate limiting
Interview Focus:
How would you implement request validation in API Gateway?
Explain API Gateway stages and stage variables
How do Lambda authorizers work and when would you use them?
What's the difference between REST APIs and HTTP APIs?
Key Features:
Path-based routing: /api/v1/* → Service A, /images/* → Service B
Hostname-based routing: [Link] → Service A, [Link] →
Service B
Host headers and HTTP methods: Fine-grained routing rules
Sticky sessions: Session affinity based on duration or cookie
Health checks: Target group health monitoring
SSL/TLS termination: Decrypt HTTPS traffic
Interview Focus:
How do you configure path-based routing with an ALB?
What makes a target unhealthy and how are requests handled?
How would you implement sticky sessions and when?
Difference between ALB and Network Load Balancer (NLB)?
Database Services
RDS (Relational Database Service)
What It Is:
Managed relational database service
Supports: MySQL, PostgreSQL, MariaDB, Oracle, SQL Server
Handles backups, patches, failover automatically
Key Concepts:
Multi-AZ Deployments: Synchronous replication to standby instance
Automatic failover if primary fails
~1-2 minute failover time
Double cost but high availability
Read Replicas: Asynchronous replication for read scaling
Can be in different regions (for DR)
Can promote replica to standalone database
No automatic failover
Storage Tiers: General Purpose (gp2, gp3), Provisioned IOPS
gp3: Latest, good for most workloads
gp2: Previous generation, still common
io1/io2: High I/O requirements
Backups:
Automated: Retained 1-35 days
Manual: Retained indefinitely
Restore to point-in-time (within backup window)
Java Integration:
Performance Tuning:
Connection Pooling: HikariCP settings (pool size, max lifetime, idle timeout)
Query Optimization: Use EXPLAIN ANALYZE
Indexing: Strategic indexes on frequently queried columns
Parameter Store: Store connection details securely
Monitoring: RDS CloudWatch metrics (CPU, storage, connections, latency)
Common Issues:
Too many connections: Tune pool size
Slow queries: Identify with CloudWatch logs, optimize
Storage full: Auto-scaling storage in RDS
Replication lag with read replicas
Interview Focus:
When would you use Multi-AZ vs Read Replicas?
How do you handle database migration to RDS?
What's connection pooling and why is it important?
How would you debug a slow query in RDS?
DynamoDB
What It Is:
Fully managed NoSQL database
Key-value and document store
Automatic scaling with on-demand or provisioned capacity
Key Concepts:
Data Model:
Tables: Similar to tables in SQL
Items: Similar to rows (can have different attributes)
Attributes: Similar to columns (schema-less)
Primary Key:
Partition Key (hash): Determines which partition
Sort Key (range): Optional, determines order within partition
Together: Must be unique
Example:
Table: Orders
Items:
{
customerId (Partition Key): "cust-123",
orderId (Sort Key): "order-456",
timestamp: 1625097600,
items: [... product list ...],
total: 99.99
}
Capacity Modes:
Provisioned: You specify read/write capacity units
RCU: One strongly consistent read of up to 4KB/second
WCU: One write of up to 1KB/second
More predictable costs
On-Demand: Pay per request
No capacity planning
More expensive at scale
Good for variable workloads
Advanced Features:
Indexes:
Global Secondary Index (GSI): Different partition key, eventual consistency
Local Secondary Index (LSI): Same partition key, different sort key, strong
consistency
Use for alternative query patterns
DynamoDB Streams: Ordered stream of item modifications
Trigger Lambda functions
Replicate to other databases
TTL (Time To Live): Automatic item deletion
Set on an attribute
Items deleted within 48 hours
Performance Optimization:
Hot Partitions: Avoid concentrating writes on few partition keys
Sort Key Design: Use composite sort keys for range queries
Projection: Return only needed attributes to save RCU
Batch Operations: BatchGetItem, BatchWriteItem for efficiency
Query vs Scan: Always use Query over Scan when possible
Java Integration:
Consistency Models:
Strong Consistency: Read always latest data (more latency, more RCU)
Eventual Consistency: May read stale data (less latency, less RCU)
Use strong consistency for critical reads (banking, inventory)
Interview Focus:
Design a DynamoDB schema for a social media app (users, posts, followers)
When would you use GSI vs LSI?
How would you handle hot partitions?
What's the difference between Query and Scan?
How do you implement pagination with Query?
Policy Structure:
json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*",
"Condition": {
"StringEquals": {
"aws:SourceVpc": "vpc-12345"
}
}
}
]
}
Best Practices:
Principle of Least Privilege: Grant minimum necessary permissions
Role-based access: Use roles for EC2, Lambda, ECS rather than access keys
No hardcoded credentials: Use temporary credentials from STS
MFA: Enable for root account and important users
Policy conditions: Restrict by IP, time, VPC, etc.
Interview Focus:
Design IAM roles for a Java microservices architecture
What's the difference between Users and Roles?
How do you securely manage AWS credentials in applications?
Explain resource-based policies vs identity-based policies
Amazon Cognito
What It Is:
User authentication and authorization service
Managed user pools and identity pools
OpenID Connect and SAML integration
Key Components:
User Pools: Manage user authentication (signup, signin, MFA)
Identity Pools: Provide temporary AWS credentials to access services
App Clients: OAuth 2.0 application integration
Typical Flow:
JWT Tokens:
ID Token: User identity information (name, email, custom attributes)
Access Token: Used to access protected resources
Refresh Token: Used to get new ID/Access tokens
Spring Security
↓
@EnableWebSecurity + JwtAuthenticationConverter
↓
Validate JWT signature using Cognito public keys
↓
Extract user claims for authorization
Interview Focus:
Explain the Cognito user pool signup/signin flow
What's the difference between User Pools and Identity Pools?
How do you validate JWT tokens from Cognito?
How would you implement multi-factor authentication?
Subnets:
Public Subnet: Has route to Internet Gateway
Instances need public IP or Elastic IP to access internet
Good for load balancers, NAT gateways
Private Subnet: No direct internet access
Only internal communication
Access internet through NAT gateway in public subnet
Good for databases, application servers
Security Groups:
Stateful: If you allow outbound, return traffic is automatically allowed
Rules: Specify source/destination IP, protocol, port
Best Practice: Allow only what's needed
Interview Focus:
Design a VPC for a Java application
What's the difference between Security Groups and Network ACLs?
Why use private subnets for databases?
How do private subnets access the internet?
Parameter Store:
Store configuration data and secrets
Free tier available
Simpler than Secrets Manager
No automatic rotation (but can implement via Lambda)
Java Integration:
Spring Boot Application
↓
AWS SDK v2: [Link]:secretsmanager
↓
Retrieve at startup: [Link](request)
↓
Parse JSON and populate environment/configuration
Best Practice:
Interview Focus:
When would you use Secrets Manager vs Parameter Store?
How do you implement automatic secret rotation?
How would you refresh secrets in a running application?
Frontend Deployment
S3 + CloudFront
S3 (Simple Storage Service):
Object storage service
Bucket versioning, lifecycle policies, encryption
Can host static websites (HTML, CSS, JS)
1. Create bucket
2. Enable static website hosting
3. Upload React/Angular build artifacts ([Link], [Link], etc.)
4. Configure bucket policy to allow public read (optional, use CloudFront
instead)
5. Access via bucket website endpoint
CloudFront (CDN):
Content Delivery Network
Caches content at edge locations globally
Serves from location closest to user
Reduces latency and origin server load
Distribution Setup:
Caching Strategy:
Cache Control Headers: Set via S3 metadata
[Link]: Cache-Control: max-age=0 (always revalidate)
[Link]: Cache-Control: max-age=31536000 (1 year, with versioning)
images: Cache-Control: max-age=86400 (1 day)
CloudFront Features:
Origins: S3, ALB, API Gateway, custom HTTP servers
Behaviors: Different caching rules per path
Invalidation: Purge cache immediately (costs money, use sparingly)
Geo-restriction: Restrict access by country
HTTPS: Free SSL/TLS certificate with CloudFront
Origin Shield: Extra cache layer for origin protection
Environment Configuration:
Development:
- Direct S3 endpoint or CloudFront
- Point to dev API Gateway
Production:
- CloudFront distribution
- Custom domain via Route 53
- Point to prod API Gateway
- Security headers (CSP, X-Frame-Options)
Interview Focus:
How would you deploy a React app with multiple environments?
Explain cache invalidation strategies
When would you use CloudFront vs serving directly from S3?
How do you handle environment variables in a static Angular app?
CI/CD Pipelines
AWS CodePipeline
What It Is:
Managed CI/CD orchestration service
Coordinates source, build, deploy stages
Integrates with CodeBuild, CodeDeploy, and third-party tools
Pipeline Stages:
GitHub Actions
Alternative to CodePipeline:
Runs directly on GitHub
YAML workflow files in .github/workflows/
Free for public repos, included with GitHub
Example Workflow:
yaml
name: Build and Deploy
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v2
with:
java-version: '11'
- name: Build with Maven
run: mvn clean package
- name: Build Docker image
run: docker build -t my-app:${{ [Link] }} .
- name: Push to ECR
run: |
aws ecr get-login-password | docker login --username AWS --password-s
docker push $ECR_REGISTRY/my-app:${{ [Link] }}
- name: Update ECS service
run: |
aws ecs update-service \
--cluster prod \
--service my-app-service \
--force-new-deployment
CodeBuild
What It Is:
Managed build service
Runs Docker containers with build environment
Supports Java, Python, [Link], .NET, etc.
[Link]:
yaml
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to ECR...
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login
build:
commands:
- echo Build started on `date`
- mvn clean package -DskipTests
- docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
- docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.[Link].$AWS_DEF
post_build:
commands:
- echo Build completed on `date`
- docker push $AWS_ACCOUNT_ID.[Link].$AWS_DEFAULT_REGION.[Link]/$
artifacts:
files:
- [Link]
Jenkins
On-Premises/Self-Hosted:
Full control over pipeline
Integration with AWS via plugins
Common for enterprise environments
Pipeline Stages:
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Push to ECR') {
steps {
sh '''
aws ecr get-login-password | docker login --username AWS --password-s
docker build -t my-app:${BUILD_NUMBER} .
docker push $AWS_ACCOUNT_ID.[Link].$AWS_DEFAULT_REGION.[Link]
'''
}
}
stage('Deploy to ECS') {
steps {
sh '''
aws ecs update-service --cluster prod --service my-app-service --forc
'''
}
}
}
}
Interview Focus:
Design a complete CI/CD pipeline for a Java microservices application
How would you implement canary deployments?
What's the difference between CodePipeline and GitHub Actions?
How do you handle secrets (database passwords, API keys) in CI/CD?
What metrics would you monitor in a deployment pipeline?
dockerfile
# Multi-stage build for smaller image
FROM maven:3.8-openjdk-11 AS builder
WORKDIR /app
COPY . .
RUN mvn clean package -DskipTests
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=builder /app/target/[Link] [Link]
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f [Link] || exit 1
ENTRYPOINT ["java", "-jar", "[Link]"]
Optimization:
Multi-stage builds: Reduce final image size (smaller = faster deployment)
Base image: Use -slim or -alpine variants
Layer caching: Put changes near end of Dockerfile
.dockerignore: Exclude unnecessary files
yaml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/mydb
- SPRING_DATASOURCE_USERNAME=postgres
- SPRING_DATASOURCE_PASSWORD=password
depends_on:
- postgres
postgres:
image: postgres:13
environment:
POSTGRES_DB: mydb
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Communication:
- Nodes register with API Server
- Control plane sends commands to nodes
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: java-app
spec:
replicas: 3
selector:
matchLabels:
app: java-app
template:
metadata:
labels:
app: java-app
spec:
containers:
- name: java-app
image: my-registry/java-app:1.0.0
ports:
- containerPort: 8080
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
livenessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
yaml
# Service: Internal DNS and load balancing
apiVersion: v1
kind: Service
metadata:
name: java-app
spec:
type: ClusterIP # Internal only
selector:
app: java-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
---
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
spec:
serviceName: database
replicas: 3
selector:
matchLabels:
app: database
template:
metadata:
labels:
app: database
spec:
containers:
- name: database
image: postgres:13
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
Autoscaling:
yaml
# Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: java-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: java-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
Interview Focus:
Design a Kubernetes deployment for a microservices application
Explain liveness and readiness probes
How do you implement blue-green deployment in Kubernetes?
What's the difference between DaemonSets and Deployments?
How do you manage environment-specific configurations?
json
{
"metrics": {
"namespace": "MyApplication",
"metrics_collected": {
"cpu": {
"measurement": [
{
"name": "cpu_usage_idle",
"rename": "CPU_IDLE",
"unit": "Percent"
}
],
"totalcpu": false,
"metrics_collection_interval": 60
},
"mem": {
"measurement": [
{
"name": "mem_used_percent",
"rename": "MEM_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60
},
"disk": {
"measurement": [
{
"name": "used_percent",
"rename": "DISK_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60,
"resources": ["/"]
}
}
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/var/log/[Link]",
"log_group_name": "/aws/ec2/app",
"log_stream_name": "{instance_id}"
}
]
}
}
}
}
Logs:
Centralized logging from EC2, Lambda, ECS, RDS
Log Groups: /aws/lambda/function-name , /aws/ecs/service-name
Log Streams: Organized by source (container, instance, etc.)
Retention: Configure per log group
# Latency percentiles
fields @duration
| stats pct(@duration, 50), pct(@duration, 95), pct(@duration, 99)
Alarms:
Threshold-based: CPU > 80%, Error rate > 1%
Composite alarms: Multiple conditions (AND, OR)
Actions: SNS notifications, Auto Scaling, EC2 actions
Example Alarms:
High Latency:
- Metric: ALB target response time
- Threshold: > 1000ms (p95) for 5 minutes
- Action: Scale up Auto Scaling group
Java Integration:
xml
<dependency>
<groupId>[Link]</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-core</artifactId>
</dependency>
Configuration:
java
import [Link];
import [Link];
import [Link];
@Configuration
public class XRayConfig {
@Bean
public Filter TracingFilter() {
return new AWSXRayServletFilter("MyApp");
}
}
Service Map:
Interview Focus:
How would you set up monitoring for a Java microservices application?
What metrics would you alert on?
Explain centralized logging and structured logging
How do you implement distributed tracing?
Architecture Patterns
Microservices Architecture
Benefits:
Independent scaling
Technology diversity
Fault isolation
Faster deployment cycles
Challenges:
Distributed debugging
Network latency
Data consistency
Operational complexity
Typical Structure:
Communication:
- Synchronous: REST APIs
- Asynchronous: SNS/SQS, Event Streaming
Observability:
- CloudWatch Logs
- X-Ray tracing
- Prometheus metrics
Serverless Architecture
Benefits:
No server management
Pay only for execution
Automatic scaling
Challenges:
Cold starts
Limited execution time (15 minutes max)
Vendor lock-in
Testing complexity
Pattern:
Optimization:
Provisioned concurrency for critical functions
Layers for shared code and dependencies
Caching at API Gateway level
Native images (GraalVM) for faster cold starts
Event-Driven Architecture
Components:
Event source: API, database stream, queue
Event bus: SNS topic or Kinesis stream
Event consumers: Lambda, SQS, Kinesis subscribers
Pattern:
Benefits:
Decoupled services
Easy to add new consumers
Audit trail of events
Interview Focus:
Design microservices architecture for an e-commerce application
Explain eventual consistency and how to handle it
Discuss trade-offs between synchronous and asynchronous communication
How would you handle distributed transactions?
API Layer:
- API Gateway for REST endpoints
- Lambda authorizer for authentication with Cognito
- Rate limiting to prevent abuse
Microservices:
- ECS Fargate or EKS for containerized services
- Auto-scaling based on load
- Services: Product, Order, Payment, Notification, Inventory
- Shared PostgreSQL RDS for transactional data
- DynamoDB for session/cache data
- ElastiCache for hot data
Data:
- RDS Multi-AZ for durability
- Read replicas for scaling reads
- DynamoDB for high-throughput, low-latency access
- S3 for product images, customer documents
- RDS backups for disaster recovery
Communication:
- Synchronous: REST between services via ALB
- Asynchronous: SNS/SQS for order processing
- CloudWatch for centralized logging
Security:
- VPC with public/private subnets
- Security groups restrict traffic
- IAM roles for service-to-service communication
- Secrets Manager for database credentials
- Cognito for user authentication
- HTTPS/TLS throughout
CI/CD:
- GitHub for source control
- CodePipeline/GitHub Actions for CI/CD
- CodeBuild for building containers
- Deploy to ECS/EKS with rolling updates
Monitoring:
- CloudWatch alarms for key metrics
- X-Ray for distributed tracing
- CloudWatch Insights for log analysis
Q2: Your Java application has slow database queries. How would you diagnose and fix?
Expected Answer:
Diagnosis:
1. Check CloudWatch RDS metrics:
- Database CPU usage
- Read/Write latency
- IOPS utilization
- Database connections count
4. In application:
- Add Spring Boot actuator metrics
- Check connection pool statistics
- Monitor query execution time
Solutions:
1. Query Optimization:
- Use EXPLAIN ANALYZE to understand query plan
- Add indexes on frequently queried columns
- Rewrite complex joins
- Use database statistics (ANALYZE command)
2. Application Level:
- Configure HikariCP pool:
- maximumPoolSize: 10-20 (tune based on connections)
- minimumIdle: Match database connections
- maxLifetime: 30 minutes
- Use prepared statements (prevents SQL injection, enables caching)
- Batch updates instead of individual inserts
3. Infrastructure:
- Consider larger RDS instance (more CPU/memory)
- Enable RDS storage autoscaling
- Use read replicas for read-heavy queries
- Consider caching layer (ElastiCache) for hot data
4. Data Level:
- Archive old data to S3 (partition strategy)
- Normalize schema if over-denormalized
- Denormalize if over-normalized (data duplication)
Q3: How would you implement zero-downtime deployment for Java application?
Expected Answer:
For ECS:
1. Update task definition with new image:
- New task definition revision created
3. Process:
a. Spin up new tasks with updated image
b. Health checks confirm new tasks are healthy
c. ALB starts routing to new tasks
d. Old tasks drain connections (deregistration delay 30s)
e. Old tasks terminated
4. Configuration:
- Health check: /actuator/health (Spring Boot)
- Deregistration delay: 30-60 seconds
- healthy/unhealthy thresholds: 2 consecutive checks
For EKS:
1. Rolling update strategy:
maxSurge: 1 (allow 1 extra pod temporarily)
maxUnavailable: 0 (no pods go down)
2. Pod lifecycle:
- preStop hook to gracefully shutdown
- terminationGracePeriodSeconds: 30 (wait for connections to drain)
- readinessProbe: Remove from service before killing
3. Blue-Green deployment:
- Deploy new version to green environment
- Test completely
- Switch traffic from blue to green
- Keep blue as rollback option
For Lambda:
- Gradual traffic shifting: Linear, Canary, All at once
- SAM/CloudFormation Hooks for automated rollback
- Test in staging first
Q4: How would you handle database connection pool exhaustion?
Expected Answer:
Symptoms:
- "Cannot acquire a connection, pool error Timeout waiting for idle object"
- Application becomes unresponsive
- Database shows high connection count
Root causes:
1. Too many concurrent requests
2. Connections not being returned (connection leak)
3. Slow queries holding connections longer than needed
4. Connection pool too small for workload
Investigation:
1. Check HikariCP metrics:
- [Link] (current)
- [Link] (waiting)
- [Link] (timeouts)
2. Check database:
- SELECT COUNT(*) FROM information_schema.processlist
- SHOW FULL PROCESSLIST (MySQL)
- SELECT * FROM pg_stat_activity (PostgreSQL)
3. Check logs:
- Look for "Timeout waiting" errors
- Identify which queries are slow
Solutions:
1. Increase pool size:
- HikariCP: maximumPoolSize (tune upward)
- Start with: 10 + (2 × number of CPU cores)
- Monitor and adjust based on load
4. Connection validation:
- connectionTestQuery: SELECT 1
- idleTimeout: 10 minutes
- maxLifetime: 30 minutes
5. Infrastructure:
- RDS: Increase max connections parameter
- Add read replicas to distribute reads
Q5: How would you implement authentication and authorization for microservices?
Expected Answer:
Authentication (who are you):
1. User signs into Cognito User Pool:
- Username/password
- Multi-factor authentication option
4. Service-to-service:
- Assume IAM role for internal service calls
- Use SigV4 signing for AWS service calls
- Use mTLS certificates for Kubernetes
- API keys for external service calls
5. Secrets management:
- Never hardcode credentials
- Use IAM roles for EC2/ECS/Lambda
- Secrets Manager for passwords/keys
- Rotate regularly
Best practices:
- Short-lived tokens (15 minutes for access token)
- Refresh tokens longer-lived (7 days)
- Always use HTTPS
- Validate tokens on every request
- Use security headers (CORS, CSP, X-Frame-Options)
Operational Questions
Q6: Your Lambda function has high cold start latency. How would you optimize?
Expected Answer:
Diagnosis:
- CloudWatch metric: Lambda Duration
- Look for spikes when no invocations for a while
- Java cold starts typically 1-2 seconds
Optimization strategies:
1. Language/Framework:
- Use Quarkus or Micronaut (optimized for Lambda)
- GraalVM native image: 50-200ms cold start
- Reduces JAR size and startup time
2. Code optimization:
- Initialize heavy objects outside handler
- Use connection pooling
- Lazy load dependencies
- Remove unused libraries
3. Memory allocation:
- Increase memory: 1GB has 3x CPU vs 128MB
- More CPU → faster cold start
- More memory → higher cost
- Sweet spot: usually 512MB-1GB for Java
4. Provisioned concurrency:
- Keep specified number of containers warm
- Costs even when not invoked
- Use for critical functions
- Example: API with consistent traffic
6. AWS optimizations:
- EphemeralStorage: Increase to 10GB (faster disk)
- Function improvements: Use Lambda@Edge for CloudFront
- Architecture: Use Graviton processors for better perf
7. Design patterns:
- Use SQS for async processing (cold start less critical)
- Use API Gateway caching for repeated requests
- Lambda Reserved Concurrency for baseline performance
Configuration example:
- Memory: 1024 MB
- Architecture: arm64 (Graviton)
- Timeout: 60 seconds
- Ephemeral storage: 10GB
- Provisioned concurrency: 100
Q7: How would you debug a production issue with minimal log visibility?
Expected Answer:
Immediate actions:
1. Check recent changes:
- What code was deployed?
- Any infrastructure changes?
- Configuration updates?
2. Check dashboards:
- CloudWatch metrics (errors, latency, CPU)
- Application metrics (custom)
- Database performance
- Network throughput
3. Check logs:
- CloudWatch Logs groups
- Filter for ERROR level
- Look at timestamps around issue start
- Use CloudWatch Insights to correlate metrics
Query examples:
fields @timestamp, @message, @logStream | filter @message like /ERROR/ | stats count()
by @logStream
4. Distributed tracing:
- X-Ray service map
- Identify which service is slow/failing
- Trace specific requests
5. Check alarms:
- Which alarms fired?
- What thresholds were exceeded?
Systematic investigation:
1. Is it infrastructure or application?
- Check resource utilization (CPU, memory, disk)
- RDS: database connections, CPU, IOPS
2. Is it code or configuration?
- Compare current vs previous deployment
- Check environment variables
- Check database credentials working
3. Is it external dependencies?
- Can you reach RDS?
- Can you reach external APIs?
- DNS resolution working?
Q8: How would you perform a database migration with zero downtime?
Expected Answer:
Scenario: Migrate from MySQL to PostgreSQL
2. Test migration:
- Use AWS DMS (Database Migration Service)
- Perform full load test
- Verify data integrity
- Test application against target
2. Rollback procedure:
- Switch reads back to MySQL
- Change takes effect immediately
DMS handles:
- Schema conversion
- Full load of existing data
- CDC (Change Data Capture) for ongoing updates
- Validation of data consistency
Rollback strategy:
- Keep MySQL running and updated
- If issues in PostgreSQL, switch back
- PostgreSQL can temporarily write to MySQL for validation
Performance Questions
Q9: How would you optimize cost for a Java application on AWS?
Expected Answer:
Compute:
- Use Fargate Spot (70% discount) for non-critical workloads
- Reserved instances for baseline load
- Scale down during off-hours
- Right-size instances (monitor utilization)
Database:
- Use RDS Multi-AZ only if needed (doubles cost)
- Read replicas only for actual read scaling
- Use DynamoDB on-demand for variable workloads
- DynamoDB provisioned for predictable loads
- Archive old data to S3 (not in database)
Storage:
- S3 Intelligent-Tiering for automatic archiving
- Use appropriate storage class (Standard, IA, Glacier)
- Delete unused snapshots
- Use S3 lifecycle policies
Network:
- CloudFront for CDN (reduces origin calls)
- NAT gateway charges: Consider NAT instances for lower volume
- VPC endpoints for private AWS service access
- Data transfer: Keep traffic within AWS region
Lambda:
- Right-size memory allocation
- Use on-demand pricing for variable workloads
- Reserved concurrency for baseline
- Avoid unnecessary cold starts
Monitoring:
- Use AWS Cost Explorer to identify expensive services
- Set up cost anomaly alerts
- Use tagging for cost allocation
- Reserved capacity discounts
Option 1 (Expensive):
- Lambda 1GB: $50k/month
- RDS Multi-AZ: $2k/month
- Total: $52k/month
Option 2 (Optimized):
- SQS for queueing: $1k/month
- Lambda 512MB + Spot: $15k/month
- RDS Single-AZ with read replica: $1.2k/month
- DynamoDB on-demand: $3k/month
- Total: $20k/month (60% savings)
Practice Scenarios
Scenario 1: A microservice has 1% of requests timing out. Walk through your
troubleshooting.
Scenario 2: You need to deploy a new service to production with confidence. Design the
rollout strategy.
Scenario 3: Your database is running out of space. How do you handle this without
downtime?
Scenario 4: An application has inconsistent performance. Sometimes fast, sometimes slow.
Diagnose the issue.
Scenario 5: You need to reduce costs by 40% without reducing capacity. What changes
would you make?
This guide covers the full scope of your experience. Practice explaining each concept in
your own words, and be prepared to discuss trade-offs and real-world experiences you've
had. Good luck with your interview!